区分clientHeight、scrollHeight、offsetHeight

区分clientHeight、scrollHeight、offsetHeight

clientHeight、offsetHeight、scrollHeight都是用来描述DOM元素的高度的属性;对于同一个元素,它们分别表示的高度值会有所不同。具体如下:

clientHeight:

只读属性,所表示的元素高度包括:元素的内容高度(如果有下滚动条,需减去下滚动条的高度,下滚条默认高度为17px)+上下padding;不包括上下border、上下margin、下滚动条高度(如果元素有下滚动条,则clientHeight表示的高度不包含下滚动条)。

offsetHeight:

只读属性,所表示的元素高度包括:元素的内容高度(如果有下滚动条,需减去下滚动条的高度,下滚条默认高度为17px)+上下padding+上下border+下滚动条高度(如果元素有下滚动条,则offsetHeight表示的高度包含下滚动条);不包括上下margin;我们通过css设置的高度、上下padding、上下border组成了offsetHeight的值。

scrollHeight:

只读属性,如果元素内的子元素高度大于该元素,scrollHeight所表示的元素高度为:元素内子元素的高度+该元素的上下padding;如果元素内的子元素高度小于该元素,scrollHeight所表示的元素高度为:该元素的内容高度(如果有下滚动条,需减去下滚动条的高度,下滚条默认高度为17px)+该元素的上下padding,此时,与clientHeight在数值上相等。

下面两个demo可以很好地证明以上表述:

demo1(如果元素内的子元素高度大于该元素):

  • html
<div class="container">
    <div class="box"></div>
</div>
  • css
.container{
    overflow: auto;
    width: 1000px;
    height: 500px;
    padding: 20px 40px;
    border: 10px dashed #f44336;
    margin: 30px 40px;
    background: #ffeb3b;
}
.box{
    width: 500px;
    height: 2000px;
    background: #2196f3;
}

这里写图片描述

demo2(如果元素内的子元素高度小于该元素):

  • html
<div class="container">
    <div class="box"></div>
</div>
  • css(如果有下滚动条)
.container{
    overflow: scroll;
    width: 1000px;
    height: 500px;
    padding: 20px 40px;
    border: 10px dashed #f44336;
    margin: 30px 40px;
    background: #ffeb3b;
}
.box{
    width: 500px;
    height: 200px;
    background: #2196f3;
}

这里写图片描述

  • css(如果没有下滚动条)
.container{
    width: 1000px;
    height: 500px;
    padding: 20px 40px;
    border: 10px dashed #f44336;
    margin: 30px 40px;
    background: #ffeb3b;
}
.box{
    width: 500px;
    height: 200px;
    background: #2196f3;
}

这里写图片描述

总结:

1、clientHeight与offsetHeight的区别在于是否将元素的border以及下滚动条高度(如果有下滚动条)计算在内;

2、如果元素内的子元素高度小于该元素,该元素的scrollHeight与clientHeight在数值上相等;

3、如果元素内的子元素高度大于该元素,scrollHeight所表示的元素高度为:元素内子元素的高度+该元素的上下padding;

参考文献:

[1] css clientheight、offsetheight、scrollheight详解
[2] 搞清clientHeight、offsetHeight、scrollHeight、offsetTop、scrollTop
[3] js中offsetHeight、clientHeight、scrollHeight等相关属性区分总结

猜你喜欢

转载自blog.csdn.net/XuM222222/article/details/81874277
今日推荐