在做響應式布局、彈窗定位、滾動效果時,經常需要精確獲取瀏覽器窗口和屏幕的各種尺寸。JavaScript 提供了大量相關屬性,但它們含義各異、容易混淆。本文把常用屬性系統整理,並附上兼容不同瀏覽器的實現代碼。
網頁可見區域寬: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
scrollHeight:獲取對象的滾動高度。 scrollLeft:設置或獲取位於對象左邊界和窗口中目前可見內容的最左端之間的距離。 scrollTop:設置或獲取位於對象最頂端和窗口中可見內容的最頂端之間的距離。 scrollWidth:獲取對象的滾動寬度。 offsetHeight:獲取對象相對於版面或由父坐標 offsetParent 指定的父坐標的高度。 offsetLeft / offsetTop:獲取對象相對於版面或 offsetParent 的計算左側/頂端位置。 event.clientX / clientY:相對文檔的水平/垂直坐標。 event.offsetX / offsetY:相對容器的水平/垂直坐標。
IE6.0、FF1.06+:clientWidth = width + padding;offsetWidth = width + padding + border。 IE5.0/5.5:clientWidth = width - border;offsetWidth = width。 需要提醒的是,CSS 中的 margin 屬性與 clientWidth、offsetWidth、clientHeight、offsetHeight 均無關。
由於不同瀏覽器取值方式不同——Netscape 用 Window 的屬性,IE 需深入 Document 內部檢測 body,DOM 環境則要注意根元素尺寸——因此需要做兼容判斷:
代碼如下:
<script type="text/javascript"> var winWidth = 0; var winHeight = 0; function findDimensions() //函數:獲取尺寸 { //獲取窗口寬度 if (window.innerWidth) winWidth = window.innerWidth; else if ((document.body) && (document.body.clientWidth)) winWidth = document.body.clientWidth; //獲取窗口高度 if (window.innerHeight) winHeight = window.innerHeight; else if ((document.body) && (document.body.clientHeight)) winHeight = document.body.clientHeight; //通過深入 Document 內部對 body 進行檢測,獲取窗口大小 if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) { winHeight = document.documentElement.clientHeight; winWidth = document.documentElement.clientWidth; } //結果輸出至兩個文本框 document.form1.availHeight.value= winHeight; document.form1.availWidth.value= winWidth; } findDimensions();//調用函數,獲取數值 window.onresize=findDimensions;//窗口變化時實時更新 </script>
關鍵在於優先嘗試 window.innerWidth/innerHeight,再逐級降級到 body、documentElement,最後綁定 onresize 讓數值隨窗口變化實時刷新。理解這些屬性的差異,是做好精細化布局與交互的基礎。