clientHeight, offsetHeight, scrollHeight

overview

在element上有许多关于位置的属性,容易混淆,今天来稍微梳理一下

offset

一句话来理解就是,element在document中占用的位置

所以

offsetHeght = VISIBLE content & padding + border + scrollbar

offsetWidth也一样,可视的内容加上padding和border还有里面的scrollbar

如果理解了“element在document中占用的位置”这句话,那么offsetLeft和offsetTop也就很好理解,表示的就是element距离document的left和top,举个例子


  
body {
  padding: 50px;
  border: 20px solid;
  margin: 20px;
}
.block {
  width: 50px;
  height: 50px;
  border: 1px solid;
}

那么block的offsetLeft和offsetTop是多少呢

offsetLeft = 20 + 20 + 50

offsetTop也一样

在实际中offset的作用往往可以用来得到最近的相对布局元素和计算left和top

In most practical cases we can use offsetParent to get the nearest CSS-positioned ancestor. And offsetLeft/offsetTop provide x/y coordinates relative to it’s left-upper corner.

client

client可以简单理解为一个元素的可视区域,client可以分为两个部分,inside和outside

所以clientHeight表示的是element的inside部分,content + padding,不包括滚动条,clientLeft表示inside和outside的之间的距离,如果没有滚动条就是border,所以其实滚动条是算在inside和outside之间的距离上,而不是clientHeight的数值上


clientHeight, offsetHeight, scrollHeight_第1张图片
image.png

scroll

scroll表示滚动的区域

scrollHeight = ENTIRE  content & padding (visible or not)

也就是整个内容和padding部分

scrollLeft和scrollTop表示的分别是scroll element距离left和top的滚动距离,注意这两个属性是可读可写的

实际使用中可以用来扩展滚动区域

// expand the element to the full content height
element.style.height = element.scrollHeight + 'px';

reference

Element.scrollTop
What is offsetHeight, clientHeight, scrollHeight?
Geometry

你可能感兴趣的:(clientHeight, offsetHeight, scrollHeight)