精確控制元素尺寸是動態佈局、動畫、虛擬滾動的基礎。本文詳細對比 clientWidth、offsetWidth、scrollWidth、getBoundingClientRect() 等屬性/方法的差異、讀寫權限與效能特性。
| 屬性 | 包含內容 | 典型用途 |
|---|---|---|
clientWidth/Height | content + padding | 可視區尺寸、內容區實際大小 |
offsetWidth/Height | content + padding + border | 元素佈局佔用空間、碰撞檢測 |
scrollWidth/Height | 完整內容尺寸(含溢出隱藏部分) | 判斷是否有溢出、虛擬滾動內容高度 |
getBoundingClientRect() | 相對視窗的精確幾何資訊(含 transform) | 定位浮層、計算視口可見性、動畫終點 |
// 僅能設定內聯樣式,單位必須帶 px(或其他 CSS 單位)
el.style.width = '300px';
el.style.height = '200px';
// 批量設定:cssText 避免多次重排
el.style.cssText = 'width:300px;height:200px;background:#f00;';
// 切換 class 更優雅、可維護
el.classList.add('large-size');
el.offsetWidth = 300 — 唯讀屬性不可賦值。el.style.width = 300 — 缺少單位會被忽略。offsetWidth 讀取會強制觸發**強制同步佈局**,頻繁讀寫導致效能問題。批量讀取後再批量寫入。function resizeToContent(el) {
// 1. 讀取階段
const scrollH = el.scrollHeight;
const scrollW = el.scrollWidth;
// 2. 寫入階段(使用 requestAnimationFrame 避免佈局抖動)
requestAnimationFrame(() => {
el.style.height = scrollH + 'px';
el.style.width = scrollW + 'px';
});
}
若 box-sizing: border-box,width/height 包含 padding+border,clientWidth 仍只回傳 content+padding,offsetWidth 等於 CSS width。開發時務必統一專案的 box-sizing 策略。