记录js中一些计算元素宽高相关的属性和方法,理解各属性之间的区别及应用场景。
clientWidth/clientHeight
内容区域的宽度/高度,不包括边框border的宽度,含padding宽度。
.box {
background: palevioletred;
height: 100px;
width: 100px;
padding: 30px;
border: 20px solid wheat;
margin: 2px;
color: #fff;
}
以上面为例,当box-sizing:content-box
时, clientWidth
为 paddingLeft+width+paddingRight = 160 px
;
当box-sizing:border-box
时, clientWidth
为 width-borderLeft-borderRight = 60 px
;
offsetWidth/offsetHeight
整个元素的宽高,包括边框border,即 borderLeft+clientWidth+borderRight
以上图为例,当box-sizing:content-box
时, offsetWidth为200px;
当box-sizing:border-box
时, offsetWidth
为 clientWidth+borderLeft+borderRight = 100 px
;
总结:无论box-sizing
属性为何值,offsetWidth = clientWidth+borderLeft+borderRight;
style.width
和 getComputedStyle
style.width
用于获取内联样式中style属性中定义的宽高,例如元素<div id="box" style="width: 120px"></div>
<div id="box" style="width: 120px"></div>
<script>
const box = document.getElementById('box')
console.log(box.style.width) //120px
</script>
getComputedStyle
用于获取元素经历过各种优先级计算后最终样式表中的样式。使用方式window.getComputedStyle(element)
<style>
.box {
border: 1px solid rebeccapurple;
width: 200px;
}
</style>
<div id="box"></div>
<script>
const box = document.getElementById('box')
console.log( window.getComputedStyle(box).width) //200px
</script>