gogoend / blog

blogs, ideas, etc.
MIT License
9 stars 2 forks source link

了解HTML元素中的各种尺寸与位置 —— offset / scroll / client / getBoundingClientRect() #54

Open gogoend opened 4 years ago

gogoend commented 4 years ago

事实上笔者一直对DOM元素中各个元素的各种尺寸充满疑惑,有时候傻傻自己分不清元素的offset / scroll / client / getBoundingClientRect() 位置与尺寸。因此本文将尝试对这些属性的了解进行实践。

本文以知乎问题页面中右侧栏的相关属性模块为例,来对这些属性进行尝试。 下图是一个未更改相关样式的模块 —— 在右侧笔者输出了当前选中元素($0)的相关属性值 image 属性
$0.offsetHeight 374
$0.clientHeight 374
$0.scrollHeight 374
$0.getBoundingClientRect().height 374
$0.offsetWidth 296
$0.clientWidth 296
$0.scrollWidth 296
$0.getBoundingClientRect().width 296

接下来放开注释掉的样式:

height: 200px;
overflow: auto;
这里设置了容器内容的高度,同时设置了overflow值使得容器可以滚动。 再次输出: image 属性
$0.offsetHeight 200
$0.clientHeight 200
$0.scrollHeight 395
$0.getBoundingClientRect().height 200
$0.offsetWidth 296
$0.clientWidth 279
$0.scrollWidth 279
$0.getBoundingClientRect().width 296

此时,容器出现了一个垂直滚动条,占用了一部分容器宽度,因此$0.clientWidth$0.scrollWidth值略有缩小,为原来的宽度 - 滚动条宽度

继续放开注释掉的样式:

border: 4px solid #f00;
输出得到: image 属性
$0.offsetHeight 200
$0.clientHeight 192
$0.scrollHeight 395
$0.getBoundingClientRect().height 200
$0.offsetWidth 296
$0.clientWidth 271
$0.scrollWidth 271
$0.getBoundingClientRect().width 296
再将padding样式放开 image 属性
$0.offsetHeight 200
$0.clientHeight 192
$0.scrollHeight 457
$0.getBoundingClientRect().height 200
$0.offsetWidth 296
$0.clientWidth 271
$0.scrollWidth 271
$0.getBoundingClientRect().width 296