offset、client、scroll区别

offset

一句话:除了 margin 我们都要。

offsetWidth & offsetHeight

offsetWidth = cssWidth + padding + border;

offsetHeight = cssHeight + padding + border;

注意:如果将元素的box-sizing设置为border-box,offsetWidth 就等于 cssWidth。

举个例子:

#wrapper{
    100px;
    height:100px;
    padding:10px;
    margin:4px;
    border:1px solid red;
}
<div id='wrapper'></div>

输出的结果:

wrapper's offsetHeight:122px
wrapper's offsetWidth:122px

offsetLeft & offsetTop

offsetLeft & offsetTop = 相对祖先元素(position 不为 static 的元素)的偏移量;

举个例子:

wrapper 未设置 position

#wrapper{
    100px;
    height:100px;
    padding:10px;
    margin:4px;
    border:1px solid red;
}
#content{
    50px;
    height:50px;
    padding:5px;
    margin:3px;
    border:1px solid red;
}
<div id='wrapper'>
    <div id="content"></div>
</div>

输出的结果:

wrapper's offsetLeft:4px
wrapper's offsetTop:4px
content's offsetLeft:18px(相对于 html 的偏移量)
content's offsetTop:18px

将wrapper 的 position 设置为 relative

#wrapper{
    100px;
    height:100px;
    padding:10px;
    margin:4px;
    border:1px solid red;
    position:relative;
}

输出结果

content's offsetLeft:13px(相对于 warpper 元素的偏移量)
content's offsetTop:13px

client

一句话:等于 offset 去掉 border 和滚动条。

clientWidth & clientHeight

offset 减去 border 和滚动条的宽度就等于 client。

clientWidth = offsetWidth - border - scrollBar;
clientHeight = offsetHeight - border - scrollBar;

clientLeft & clientTop

没有(左侧/顶部)滚动条时,clientLeft 与 clientTop 等于 border 的宽度,有(左侧/顶部)滚动条时,等于 border 的宽度 + 滚动条的宽度。

特殊情况

当我们在获取<html>元素(document. documentElement)尺寸的时候,client 给出的是 viewport 的尺寸,即浏览器的可视区域尺寸,而 offset 给出的是<html>元素的尺寸,例如:浏览器宽度是 1920px,当修改<html>元素的宽度为 10% 时,document. documentElement.clientWidth 为 1920,document. documentElement.offsetWidth 为 192。

scroll

scrollWidth & scrollHeight

scrollWidth = clientWidth + 溢出内容尺寸;
scrollHeight = clientHeight + 溢出内容尺寸;

scrollTop & scrollLeft

scrollTop:这个元素的顶部到视口可见内容的顶部的距离,当一个元素的内容没有产生垂直方向的滚动条,那么 scrollTop 为 0,scrollLeft 同理。

除了上述的方法外,还有 getComputedStyle 和 getBoundingClientRect 两个方法能获取到详细的尺寸。

 

Method

getComputedStyle()

getComputedStyle() 获取的是元素 css 定义的属性,css 中是什么就返回什么,举个例子:

#wrapper{
    100px;
    height:100px;
    padding:10px;
    margin:4px;
    border:1px solid red;
}
console.log(document.querySelector('#wrapper').getComputedStyle().width)

输出的结果:250px

getBoundingClientRect()

getBoundingClientRect() 获取的是元素的位置信息:left、right、top、bottom 以及 width、height。

返回的 width = offsetWidth,height = offsetHeight。

原文地址:https://www.cnblogs.com/yang1997/p/12194450.html