在進行 HTML5 移動端開發(例如在 Android 下)時,往往需要獲取屏幕的實際尺寸以做自適應佈局。下面先給出一段可直接測試的代碼,再梳理相關屬性的含義與浏覽器差異。
<html> <script> function a(){ document.write( "屏幕分辨率為:"+screen.width+"*"+screen.height +"<br />"+ "屏幕可用大小:"+screen.availWidth+"*"+screen.availHeight +"<br />"+ "網頁可見區域寬:"+document.body.clientWidth +"<br />"+ "網頁可見區域高:"+document.body.clientHeight +"<br />"+ "網頁可見區域寬(包括邊線的寬):"+document.body.offsetWidth +"<br />"+ "網頁可見區域高(包括邊線的寬):"+document.body.offsetHeight +"<br />"+ "網頁正文全文寬:"+document.body.scrollWidth +"<br />"+ "網頁正文全文高:"+document.body.scrollHeight +"<br />"+ "網頁被卷去的高:"+document.body.scrollTop +"<br />"+ "網頁被卷去的左:"+document.body.scrollLeft +"<br />"+ "網頁正文部分上:"+window.screenTop +"<br />"+ "網頁正文部分左:"+window.screenLeft +"<br />"+ "屏幕分辨率的高:"+window.screen.height +"<br />"+ "屏幕分辨率的寬:"+window.screen.width +"<br />"+ "屏幕可用工作區高度:"+window.screen.availHeight +"<br />"+ "屏幕可用工作區寬度:"+window.screen.availWidth ); } </script> <body onload="a()" > </body> </html>
scrollHeight:對象的滾動高度;scrollLeft:設置或獲取對象左邊界到可見內容最左端的距離;scrollTop:設置或獲取對象頂端到可見內容最頂端的距離;scrollWidth:對象的滾動寬度;offsetHeight/offsetWidth:相對於版面或 offsetParent 指定父坐標的高/寬;offsetLeft/offsetTop:相對於父坐標的左/頂位置;event.clientX/Y:相對文檔的水平/垂直坐標;event.offsetX/Y:相對容器的坐標。
IE6.0、FF1.06+:
clientWidth = width + padding;clientHeight = height + padding;offsetWidth = width + padding + border;offsetHeight = height + padding + border。
IE5.0/5.5:
clientWidth = width - border;clientHeight = height - border;offsetWidth = width;offsetHeight = height。
需要一提的是:CSS 中的 margin 屬性與 clientWidth、offsetWidth、clientHeight、offsetHeight 均無關。
掌握 screen、document.body 與 window 這幾組屬性的區別,就能在各種分辨率與浏覽器環境下準確地拿到想要的尺寸。