前端開發頻繁需要獲取視窗可視區、文檔完整尺寸、捲軸位置、螢幕解析度等數值。不同屬性在不同瀏覽器、模式(Quirks/Standards)下表現不一。本文整理完整屬性速查表、差異對照與最佳實踐封裝函數。
| 需求 | 標準屬性 (推薦) | 備註 |
|---|---|---|
| 視窗可視寬度 | window.innerWidth | 含垂直捲軸寬度 |
| 視窗可視高度 | window.innerHeight | 含水平捲軸高度 |
| 文檔完整寬度 | document.documentElement.scrollWidth | 含溢出內容 |
| 文檔完整高度 | document.documentElement.scrollHeight | 含溢出內容 |
| 水平捲動距離 | window.scrollX / document.documentElement.scrollLeft | 別名 pageXOffset |
| 垂直捲動距離 | window.scrollY / document.documentElement.scrollTop | 別名 pageYOffset |
| 元素相對視窗位置 | element.getBoundingClientRect() | 回傳 {top,left,right,bottom,width,height} |
| 螢幕解析度寬 | screen.width | 物理像素 |
| 螢幕解析度高 | screen.height | 物理像素 |
| 可用工作區寬 | screen.availWidth | 扣除任務列 |
| 可用工作區高 | screen.availHeight | 扣除任務列 |
| 事件滑鼠座標 (相對視窗) | event.clientX / clientY | 不含捲動 |
| 事件滑鼠座標 (相對文檔) | event.pageX / pageY | 含捲動 |
| 事件滑鼠座標 (相對元素) | event.offsetX / offsetY | 相對 target 元素 |
// Standards Mode (DOCTYPE html)
document.documentElement.clientWidth // 視窗可視寬 (不含捲軸)
document.body.clientWidth // 不可靠
// Quirks Mode (無 DOCTYPE)
document.body.clientWidth // 視窗可視寬
document.documentElement.clientWidth // 0 或錯誤
結論:永遠宣告 <!DOCTYPE html> 啟用標準模式,統一使用 document.documentElement (即 <html>) 獲取視窗尺寸。
const DomUtils = {
// 視窗可視尺寸
viewport: () => ({
width: window.innerWidth || document.documentElement.clientWidth,
height: window.innerHeight || document.documentElement.clientHeight
}),
// 文檔完整尺寸
documentSize: () => ({
width: Math.max(
document.body.scrollWidth, document.documentElement.scrollWidth,
document.body.offsetWidth, document.documentElement.offsetWidth,
document.documentElement.clientWidth
),
height: Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.documentElement.clientHeight
)
}),
// 捲動位置
scrollPos: () => ({
x: window.scrollX || document.documentElement.scrollLeft,
y: window.scrollY || document.documentElement.scrollTop
}),
// 元素相對文檔座標
offset: (el) => {
const rect = el.getBoundingClientRect();
const scroll = DomUtils.scrollPos();
return { top: rect.top + scroll.y, left: rect.left + scroll.x };
}
};
// 使用
console.log(DomUtils.viewport()); // {width: 1920, height: 937}
console.log(DomUtils.scrollPos()); // {x: 0, y: 120}
<form id="sizeForm">
視窗寬: <input name="availWidth" readonly><br>
視窗高: <input name="availHeight" readonly>
</form>
<script>
function update() {
const v = DomUtils.viewport();
const f = document.forms.sizeForm;
f.availWidth.value = v.width;
f.availHeight.value = v.height;
}
update();
window.addEventListener('resize', update);
</script>
document.body.clientWidth 在 body 有 margin 時包含 margin,不可靠。offsetWidth/Height 含 border + padding + scrollbar(若元素有 overflow:scroll)。innerWidth 為 **CSS 像素**,非物理像素;需搭配 devicePixelRatio。getBoundingClientRect() 回傳值為浮點數(亞像素),比較時請用 Math.round。