核心尺寸屬性對照
| 屬性 | 意義 | 包含內容 |
document.body.clientWidth | 可視區寬度 | 內容 + padding,不含邊框/捲軸 |
document.body.clientHeight | 可視區高度 | 內容 + padding,不含邊框/捲軸 |
document.body.offsetWidth | 可視區寬度 | 內容 + padding + border + 捲軸 |
document.body.offsetHeight | 可視區高度 | 內容 + padding + border |
document.body.scrollWidth | 內容實際寬度 | 含溢出隱藏內容 |
document.body.scrollHeight | 內容實際高度 | 含溢出隱藏內容 |
document.body.scrollTop | 文件被捲去的高度 (FF/Chrome) | — |
document.documentElement.scrollTop | 文件被捲去的高度 (IE/標準模式) | — |
document.body.scrollLeft | 文件被捲去的左側距離 | — |
window.screenTop / screenY | 視窗相對螢幕頂部座標 | — |
window.screenLeft / screenX | 視窗相對螢幕左側座標 | — |
window.screen.height | 螢幕解析度高度 | — |
window.screen.width | 螢幕解析度寬度 | — |
window.screen.availHeight | 螢幕可用工作區高度 | 扣除工作列 |
window.screen.availWidth | 螢幕可用工作區寬度 | — |
window.screen.colorDepth | 螢幕色深 | 如 24、30 |
window.screen.deviceXDPI | 螢幕水平 DPI | — |
window.innerHeight | 瀏覽器視窗可視區高度 (含捲軸) | 標準模式下同 clientHeight |
window.innerWidth | 瀏覽器視窗可視區寬度 | — |
相容性取值最佳實踐
// 文件可視區尺寸(相容標準/怪異模式)
var clientWidth = document.compatMode === 'CSS1Compat'
? document.documentElement.clientWidth
: document.body.clientWidth;
var clientHeight = document.compatMode === 'CSS1Compat'
? document.documentElement.clientHeight
: document.body.clientHeight;
// 捲動距離(相容)
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
// 視窗尺寸(現代瀏覽器)
var winWidth = window.innerWidth || document.documentElement.clientWidth;
var winHeight = window.innerHeight || document.documentElement.clientHeight;
實用封裝函式
function getPageDimensions() {
var d = document, de = d.documentElement, db = d.body;
var mode = d.compatMode === 'CSS1Compat';
var root = mode ? de : db;
return {
// 視窗可視區
viewport: { width: de.clientWidth, height: de.clientHeight },
// 文件總尺寸
document: { width: de.scrollWidth, height: de.scrollHeight },
// 捲動位置
scroll: { top: de.scrollTop || db.scrollTop, left: de.scrollLeft || db.scrollLeft },
// 螢幕資訊
screen: {
width: screen.width, height: screen.height,
availWidth: screen.availWidth, availHeight: screen.availHeight,
colorDepth: screen.colorDepth
}
};
}
console.log(getPageDimensions());
視覺化示意
+--------------------------------------------------+ <-- window.screen (螢幕)
| 瀏覽器視窗 |
| +--------------------------------------------+ | <-- window.innerWidth/Height (視窗可視區)
| | 文件內容 | |
| | (scrollWidth/scrollHeight) | |
| | | |
| | 捲動區域 (scrollTop/scrollLeft) | |
| +--------------------------------------------+ |
+--------------------------------------------------+