本文示範如何使用 jQuery 取得 document 與 window 物件的寬度與高度。
<!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 開發有所幫助。