做響應式或彈窗定位時,經常需要取得各種「寬高」。以下把原生 JavaScript 與 jQuery 的常用寫法一次整理清楚。
網頁可見區域寬: document.body.clientWidth 網頁可見區域高: document.body.clientHeight 網頁可見區域寬(含邊線): document.body.offsetWidth 網頁可見區域高(含邊線): document.body.offsetHeight 網頁正文全文寬: document.body.scrollWidth 網頁正文全文高: document.body.scrollHeight 網頁被捲去的高: document.body.scrollTop 網頁被捲去的左: document.body.scrollLeft 網頁正文部分上: window.screenTop 網頁正文部分左: window.screenLeft 螢幕解析度的高: window.screen.height 螢幕解析度的寬: window.screen.width 螢幕可用工作區高: window.screen.availHeight 螢幕可用工作區寬: window.screen.availWidth
$(document).ready(function(){
alert($(window).height()); // 視窗可視區域高度
alert($(document).height()); // 文件高度
alert($(document.body).height()); // body 高度
alert($(document.body).outerHeight(true)); // body 總高(含 border、padding、margin)
alert($(window).width()); // 視窗可視區域寬度
alert($(document).width()); // 文件寬度
alert($(document.body).width()); // body 寬度
alert($(document.body).outerWidth(true)); // body 總寬(含 border、padding、margin)
});
要點在於分辨幾組概念:clientWidth/Height 是可視區、scrollWidth/Height 是完整內容、offsetWidth/Height 含邊框;而 jQuery 的 outerWidth(true)/outerHeight(true) 會把 margin 也計入,是最完整的尺寸。