DIV CSS 佈局教程網

JavaScript 網頁定位與尺寸屬性詳解
編輯:JavaScript綜合知識     

進行元素定位、彈窗計算或滾動處理時,往往需要精確掌握各種尺寸屬性。本文系統整理這些屬性的含義,以及 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

HTML 精確定位屬性

scrollHeight: 獲取對象的滾動高度
scrollLeft: 設置或獲取位於對象左邊界和窗口中目前可見內容的最左端之間的距離
scrollTop: 設置或獲取位於對象最頂端和窗口中可見內容的最頂端之間的距離
scrollWidth: 獲取對象的滾動寬度
offsetHeight: 獲取對象相對於版面或由父坐標 offsetParent 屬性指定的父坐標的高度
offsetLeft: 獲取對象相對於版面或由 offsetParent 屬性指定的父坐標的計算左側位置
offsetTop: 獲取對象相對於版面或由 offsetParent 屬性指定的父坐標的計算頂端位置
event.clientX 相對文檔的水平座標
event.clientY 相對文檔的垂直座標
event.offsetX 相對容器的水平坐標
event.offsetY 相對容器的垂直坐標

IE 與 Firefox 的差異

在 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 等值皆無關。

DOCTYPE 的關鍵影響

實務上常遇到「明明寫了 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 與 Firefox 中,document.body 系列代表 BODY 物件尺寸,document.documentElement 系列代表可見區域尺寸;而 Opera 則相反。若未宣告標準,IE 下 document.documentElement.clientWidth 會是 0。因此,务必在頁面頂部加上標準 DOCTYPE,各瀏覽器的行為才會一致可預期。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved