在做自適應布局或全屏效果時,我們常常需要知道整個文檔或瀏覽器窗口的尺寸。jQuery 讓這件事變得很簡單。本文用實例演示如何獲取。
實現方法
直接把 $(document) 或 $(window) 當作對象,調用 width()/height() 即可取得對應尺寸。下麵點擊按鈕會彈出文檔與窗口的寬高:
代碼示例
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("button").click(function(){
var txt="";
txt+="Document width/height: " + $(document).width();
txt+="x" + $(document).height() + "\n";
txt+="Window width/height: " + $(window).width();
txt+="x" + $(window).height();
alert(txt);
}); </script>
</head>
<body>
<button>Display dimensions of document and window</button>
</body>
</html>
要點
$(document) 代表整個文檔,其尺寸會隨內容多少而變化;$(window) 代表瀏覽器視窗,即用戶當前可見區域。區分兩者,才能在不同場景下取到正確的尺寸值。
希望本文對你的 jQuery 程序設計有所幫助。