做滾動、置頂、彈窗居中或拖拽效果時,難免要計算各元素的位置與尺寸。本文彙整了常用的定位屬性,並釐清 IE 與 Firefox 等瀏覽器間的差異。
網頁可見區域寬: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:設置或獲取對象左邊界與 currently 可見內容最左端之間的距離。
scrollTop:設置或獲取對象頂端與可見內容最頂端之間的距離。
scrollWidth:獲取對象的滾動寬度。
offsetHeight:獲取對象相對於版面或 offsetParent 指定父坐標的高度。
offsetLeft:獲取對象相對父坐標的左側位置。
offsetTop:獲取對象相對父坐標的頂端位置。
event.clientX / clientY:相對文檔的水平/垂直坐標。
event.offsetX / offsetY:相對容器的水平/垂直坐標。
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 均無關。
實戰中曾遇到這樣的狀況:更換頁面版式後,document.documentElement.clientWidth 取到的寬度竟為 0。排查後發現,原因是新頁面缺少了 W3C 標準的 DOCTYPE 引用,導致該屬性失效:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
加上這行標准聲明後:
在 IE 中:document.body.clientWidth 為 BODY 對象寬度;document.documentElement.clientWidth 為可見區域寬度。
在 Firefox 中:同上,body 為 BODY 寬度,documentElement 為可見區域寬度。
在 Opera 中:document.body.clientWidth 為可見區域寬度,documentElement.clientWidth 為頁面對象寬度(BODY 寬度加上 margin)。
而未定義 W3C 標準時,IE 下 documentElement.clientWidth 會返回 0,Firefox 與 Opera 則返回頁面對象寬度。可見,養成在頁面頂部加上 DOCTYPE 的習慣,能避免大量跨瀏覽器的定位 bug。