相关属性解释见专栏其他文章介绍
只讨论块级元素的情况下:
(1)元素没有滚动条,且没有border-top, border-bottom时,三者相等
(2)元素没有垂直滚动条时,scrollHeight,clientHeight相等
(3)元素有垂直滚动条,且没有border-top, border-bottom时,clientHeight和offsetHeight相等
(4)元素有垂直滚动条,且有border-top或 border-bottom时,三者不相等
一般获取元素高度用offsetHeight,涉及到元素滚动相关的场景则会用到scrollHeight和clientHeight。
JS在线编辑器,JS在线运行,在线演示,调试测试代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109<style> * { margin: 0; box-sizing: border-box; } #father1 { width: 150px; height: 150px; padding: 10px; background: red; overflow: auto; } #son1 { width: 50px; height: 50px; background: blue; line-height: 50px; text-align: center; color: #fff; } #father2 { margin-top: 10px; width: 150px; height: 150px; padding: 10px; border: 5px solid green; background: red; overflow: auto; } #son2 { width: 250px; height: 50px; background: blue; line-height: 50px; text-align: center; color: #fff; } #father3 { margin-top: 10px; width: 150px; height: 150px; padding: 10px; background: red; overflow: auto; } #son3 { width: 50px; height: 250px; background: blue; line-height: 50px; text-align: center; color: #fff; } #father4 { margin-top: 10px; width: 150px; height: 150px; padding: 10px; border: 5px solid green; background: red; overflow: auto; } #son4 { width: 50px; height: 250px; background: blue; line-height: 50px; text-align: center; color: #fff; } </style> <body> <div id="father1"> <div id="son1"> son1 </div> </div> <div id="father2"> <div id="son2"> son2 </div> </div> <div id="father3"> <div id="son3"> son3 </div> </div> <div id="father4"> <div id="son4"> son4 </div> </div> </body> <script> let father1 = document.getElementById("father1"); // 元素没有滚动条,且没有border-top, border-bottom时,三者相等 console.log(father1.scrollHeight, father1.clientHeight, father1.offsetHeight) // 150,150, 150 let father2 = document.getElementById("father2"); // 元素没有垂直滚动条时,scrollHeight,clientHeight相等 console.log(father2.scrollHeight, father2.clientHeight, father2.offsetHeight) // 133,133, 150 let father3 = document.getElementById("father3"); // 元素有垂直滚动条,且没有border-top, border-bottom时,clientHeight和offsetHeight相等 console.log(father3.scrollHeight, father3.clientHeight, father3.offsetHeight) // 270,150,150 let father4 = document.getElementById("father4"); // 元素有垂直滚动条,且有border-top或 border-bottom时,三者不相等 console.log(father4.scrollHeight, father4.clientHeight, father4.offsetHeight) // 270,150,150 </script>
最后
以上就是小巧大叔最近收集整理的关于Element属性:scrollHeight,clientHeight,offsetHeight区别的全部内容,更多相关Element属性:scrollHeight内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复