DOM – Dimension (offset, client, computed, rect)

前言

很多年前有記入過一篇 box-sizing 和 dom width.

想想也挺可悲的, 那年我是負責後端的, 卻要幫着前端去學習這些知識來解決問題...

也好, 現在 full stack, 也算沒有浪費當年的努力. 這篇是翻新版本.

 

和 Dimension 相關的屬性

我這裏以 div height 作爲例子. 你把它們都換成 width 理解也是一樣的.

offset-height

client-height

height (getComputedStyle)

scroll-height

rect height (getBoundingClientRect)

以上就是常見的高度

 

影響 dimension 的屬性

它們會被

box-sizing

border

padding

scale 影響

但不受 margin, outline 影響 (許多人誤以爲會)

 

各個屬性計算

offset-height

它是 border-block + padding-block + height

紅色是 border, 粉紅色是 padding, 右邊紅線表示它計算的範圍

 

client-height

它是 padding-block + height, 對比 offset-height 少了 border, 

注意 scrollbar height 是不包括在內的哦.

 

height (getComputedStyle)

height 的計算 depend on box-sizing

border-box 情況下, height 包括 padding.

content-box 情況下, heigth 不包括 padding 和 border (當然也不包括 scrollbar height, 記住 scrollbar 的位置是在 padding 之外, border 之內)

 

scroll-height (對標 client-height)

在 hug content 的情況下, scroll-height 和 client-height 始終是一致的.

只有在 overflow-y: auto 的情況下才會使用到 scroll-height. (注意: visiable 情況下 scroll-height 的計算和 auto 是不同的哦, 我也沒有搞懂, 但一般場景都是 auto 嘛, 以後再研究唄)

當 overflow-y 的時候, client-height 就變小了.

這個時候通過 scroll-height 就可以拿到原本的 client-height 的尺寸.

 

rect height (getBoundingClientRect) (對標 offset-height)

在沒有 scale 的情況下, 它和 offset-height 始終保持一致.

有 scale 的情況下, 它獲取的是 scale 之後的高度. 比如 offset-height 是 100px, scale 1.5

那麼 reat height 就是  100 x 1.5 = 150px

 

經典圖片

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章