在 JavaScript 中,clientHeight、offsetHeight、scrollHeight、clientTop、offsetTop、scrollTop 等屬性經常讓人混淆。釐清它們的差異,有助於處理版面與滾動相關問題。
clientHeight 表示元素可視區域高度,包含 padding,但不包含 border、margin 與滾動條。
若元素有上下 padding,clientHeight 會是內容高度加上 padding。
offsetHeight 包含元素高度、padding、border 與水平滾動條。
因此它通常會比 clientHeight 大,因為多了 border 與滾動條。
scrollHeight 表示內容的實際高度。若內容沒有溢出,它會等於 clientHeight;若有滾動條,則會大於 clientHeight。
clientTop 通常與 border 寬度有關;offsetTop 表示元素距離上層定位參照物的位置;scrollTop 則表示目前滾動條向下捲動的距離。
const w = document.documentElement.clientWidth || document.body.clientWidth;
const h = document.documentElement.clientHeight || document.body.clientHeight;
這類寫法常用於取得瀏覽器可視區域寬高,並兼顧不同瀏覽器的相容性。