DOM – Dimension & Coordinate (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

有没有 scollbar 影响

但不受 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 的尺寸.

容易混淆的情况: 

假设出现了 horizontal scrollbar, 请问 scroll-height 和 client-height 一样吗?

答案是 yes. 因为那是 horizontal scrollbar, 仅代表 width 的内容超过了, height 并没有, 而 scroll-height 是看有没有 vertical scrollbar 的出现.

同时 client-height 会少算 horizontal scrollbar 同样的 scroll-height 也会少算 horizontal scrollbar.

 

rect height (getBoundingClientRect) (对标 offset-height)

在没有 scale 的情况下, 它和 offset-height 始终保持一致.

有 scale 的情况下, 它获取的是 scale 之后的高度. 比如 offset-height 是 100px, scale 1.5

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

也可以参考这里

 

经典图片

 

MouseEvent 的 Coordinate

mouse event 里有 4 种 coordinate info.

分别是 page, screen, client, offset

场景说明:

2 个 section 2 个 box

offset coordinate

event.offsetX, event.offsetY

event listening 的 target element 和 mouse click 点之间的距离 (AKA target relative)

注意 parent child 冒泡的情况

假设 parent pink color div 有 mouseenter event

当 mouse 进入 parent pink color div。它的 offset 对标的是 parent div。上图的第一个红点。

当 mouse 进入 child blue color div。它的 offset 对标换成了 child div,不再是 parent div 了。

虽然 event 只绑定在 parent div,但是 offset x,y 认的是最靠近的 offset element。

另外一点需要注意,当有 transform 的时候

虽然 img 有 translate 了,但是 mouse click 图片左上角依然拿到 0,0

img scale(2),虽然 mouse click 的距离 actual 是 220,80 但是获取到的是 110, 40,因为放大了一倍,所以少了一半。

这就是它的效果。注意咯

screen coordinate

event.screenX, event.screenY

mouse click 点和 screen 的距离. 注意哦, 我的 browser 是缩小的, 它依然是计算到最外面 monitor screen 的距离. (AKA screen relative)

client coordinate

event.clientX, event.clientY

clientX, Y 是最常被使用到的. 它和 getBoundingClientRect x,y 一样. (AKA window relative)

page coordinate

page 和 client 类似, 只是它有算 scroll, 所以会比 client 多. (AKA document relative)

 

posted @ 2022-11-05 12:17  兴杰  阅读(41)  评论(0编辑  收藏  举报