获取元素高度
一、基础:理清clientHeight、offsetHeight、scrollHeight、offsetTop、scrollTop区别
图文可见:https://blog.csdn.net/qq_35430000/article/details/80277587
说的非常详细,这边列表总结如下:
名称 | 范围 |
---|---|
clientHeight | content高度(即包括上下padding) |
offsetHeight | content高度+上下border |
scrollHeight | 元素可滚动时,content实际高度;因此scrollHeight恒>=offsetHeight |
offsetTop | 在有滚动条时,滚动条向下滚动的距离也就是元素顶部被遮住部分的高度,无滚动条时为0 |
scrollTop | 当前元素顶部距离最近父元素顶部的距离,和有没有滚动条无关。 |
如果要获取margin值怎么取?
// ele 表示指定元素dom节点
const marginBt = parseFloat(window.getComputedStyle(ele).marginBottom)
二、获取滚动元素高度
(以vue为例)
<div $ref="listheight">
......
</div>
const listheight = this.$refs.listheight.scrollHeight
三、手动计算指定子元素高度
let chil = this.$refs.listheight.children;
// 可在for循环中获取任意的子元素,此处为所有元素的offsetHeight以及marginBottom值
let calculateHeight = 0;
for(var i = chil.length - 1; i >= 0; i--) {
calculateHeight += chil[i].offsetHeight + parseFloat(window.getComputedStyle(chil[i]).marginBottom);
}
参考:
https://blog.csdn.net/qq_35430000/article/details/80277587