clientWidth offsetWidth的区别

记录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时, clientWidthpaddingLeft+width+paddingRight = 160 px
在这里插入图片描述

box-sizing:border-box时, clientWidthwidth-borderLeft-borderRight = 60 px

offsetWidth/offsetHeight

整个元素的宽高,包括边框border,即 borderLeft+clientWidth+borderRight
在这里插入图片描述
以上图为例,当box-sizing:content-box时, offsetWidth为200px;
在这里插入图片描述

box-sizing:border-box时, offsetWidthclientWidth+borderLeft+borderRight = 100 px
总结:无论box-sizing属性为何值,offsetWidth = clientWidth+borderLeft+borderRight;

style.widthgetComputedStyle

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值