问题:在某些情况下,.getComputedStyle()
似乎会返回元素的height
属性的不完整/不正确的值。现在我很担心。是否知道为其他属性返回不可预测或不正确的值?
Backstory:我一直在使用.getComputedStyle()
,直到我注意到它返回的元素高度似乎是不正确的值。所以我用其他几种方法对它进行了测试。
在下面的简单测试代码中,所有这些返回400,这是测试元素的正确高度。
.offsetHeight
.scrollHeight
.clientHeight
.getBoundingClientRect().height
然而,.getComputedStyle().height
返回300px,这是在应用填充之前元素的高度。
'use strict';
window.addEventListener('load', measureDiv)
function measureDiv() {
console.log('offsetHeight = ' +document.querySelector('.container').offsetHeight);
console.log('scrollHeight = ' +document.querySelector('.container').scrollHeight);
console.log('clientHeight = ' +document.querySelector('.container').clientHeight);
console.log('getBoundingClientRect().height = ' +document.querySelector('.container').getBoundingClientRect().height);
console.log('getComputedStyle().height = ' +window.getComputedStyle(document.querySelector('.container')).height);
}
body {
margin: 0;
padding: 0;
}
.container {
margin: 120px;
padding: 50px;
background-color: green;
}
.box_1 {
padding: 20px;
background-color: blue;
}
.image_container {}
<div class="container">
<div class="box_1">
<div class="image_container"><img src="https://www.cis.rit.edu/~cnspci/courses/common/images/checkerboard-256x256.jpg"></div>
</div>
</div>