1. 程式人生 > >js獲取螢幕高度寬度解析度問題,當css3的@media查詢寫法不能解決問題時請看這個

js獲取螢幕高度寬度解析度問題,當css3的@media查詢寫法不能解決問題時請看這個

當css的@media查詢寫法如下:

@media screen and (max-width: 1920px) {
    .feature-table {

      height: 980px;background-color: #AAAAAA;    

    }

}
@media screen and (max-width: 1809px) {
    .feature-table {
        height: 850px;background-color: #AAAAAA;
    }
}
@media screen and (max-width: 1559px) {
    .feature-table {
        height: 700px;background-color: #AAAAAA;
    }
}
@media screen and (max-width: 1360px) {
    .feature-table {
        height: 500px;background-color: #AAAAAA;
    }
}
@media screen and (max-width: 1309px) {
    .feature-table {
        height: 700px;background-color: #AAAAAA;
    }
}
@media screen and (max-width: 1059px) {
    .feature-table {
        height: 400px;background-color: #AAAAAA;
    }
}
@media screen and (max-width: 809px) {
    .feature-table {
        height: 300px;background-color: #AAAAAA;
    }
}

它根據螢幕解析度的寬度去設定id為feature-table的元素的高度和背景色,但是存在如下情況1920*1200與1920*1080兩種解析度的寬度一樣,高度不一樣。從上面的程式碼走向來說,id為feature-table的元素的高度都會被設成980px,有可能在1920*1200解析度下,該元素正好鋪滿,而1920*1080下溢位影響顯示效果。

但是css3中好像沒有@media screen and (max-height: 809px) {}的寫法,因此可以藉助js獲取螢幕的高度,根據螢幕的高度去顯示內容。程式碼如下

<!DOCTYPE html>

<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div  id="size">
asdasda
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
// 測試引用是否成功

$(document).ready(function(e) {

      var s = "";   

      s += " 網頁可見區域寬:"+ document.body.clientWidth+"\n";    
      s += " 網頁可見區域高:"+ document.body.clientHeight+"\n";    
      s += " 網頁可見區域寬:"+ document.body.offsetWidth + " (包括邊線和滾動條的寬)"+"\n";    
      s += " 網頁可見區域高:"+ document.body.offsetHeight + " (包括邊線的寬)"+"\n";    
      s += " 網頁正文全文寬:"+ document.body.scrollWidth+"\n";    
      s += " 網頁正文全文高:"+ document.body.scrollHeight+"\n";    
      s += " 網頁被捲去的高(ff):"+ document.body.scrollTop+"\n";    
      s += " 網頁被捲去的高(ie):"+ document.documentElement.scrollTop+"\n";    
      s += " 網頁被捲去的左:"+ document.body.scrollLeft+"\n";    
      s += " 網頁正文部分上:"+ window.screenTop+"\n";    
      s += " 網頁正文部分左:"+ window.screenLeft+"\n";    
      s += " 螢幕解析度的高:"+ window.screen.height+"\n";    
      s += " 螢幕解析度的寬:"+ window.screen.width+"\n";    
      s += " 螢幕可用工作區高度:"+ window.screen.availHeight+"\n";    
      s += " 螢幕可用工作區寬度:"+ window.screen.availWidth+"\n";    
      s += " 你的螢幕設定是 "+ window.screen.colorDepth +" 位彩色"+"\n";    
      s += " 你的螢幕設定 "+ window.screen.deviceXDPI +" 畫素/英寸"+"\n";    
      alert(s);
  //當螢幕高度為1200px時,增加背景色
  if(window.screen.height==1200){
$("#size").css("background-color","#121111");
}
  });
</script>
</body>

</html>

這中貌似很難用css寫,最好就是js來獲取高度後,動態修改其他元素、