Does getBoundingClientRect().width
and height
属性,同时返回值包括元素的填充和边框?
TLDR;
它将始终返回尺寸边框框(下面的绿色框),其中包含内容区, 填充区域 and 边区,如定义在CSS 盒子模型 https://drafts.csswg.org/css2/#box-model.
宽度样式
然而,决不能混为一谈内容宽度(元素布局的属性)和样式宽度(对元素布局的约束,width: xxx;
规则),这是非常不同的事情。这box-sizing
只会影响是否样式宽度约束应包括border and padding, 或不。
举例说明
在第一个片段中,我们使用box-sizing: border-box
规则使得样式宽度 == 边框 + 内边距 + 内容宽度。的结果getBoundingClientRect().width
is 140
,它等于样式宽度.
var x = document.getElementById("x");
console.log('getBoundingClientRect().width =', x.getBoundingClientRect().width);
console.log('getComputedStyle(x).width =', getComputedStyle(x).width);
#x {
border: 20px solid blue;
padding: 10px;
width: 140px;
box-sizing: border-box;
}
<div id=x>Border Box</div>
在第二个片段中,我们使用box-sizing: content-box
规则使得样式宽度==内容宽度。的结果getBoundingClientRect().width
还是140
因为总和 of border + padding + 内容宽度 没有改变, only 样式宽度已经改变。
var y = document.getElementById("y");
console.log('y.getBoundingClientRect().width =', y.getBoundingClientRect().width);
console.log('getComputedStyle(y).width =', getComputedStyle(y).width);
#y {
border: 20px solid blue;
padding: 10px;
width: 80px;
box-sizing: content-box;
}
<div id=y>Content Box</div>
参考
- MDN | CSS盒子模型简介 https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model
- CSSWG | CSS2(盒子模型) https://drafts.csswg.org/css2/#box-model
- MDN | Element.getBoundingClientRect() https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)