3

问题:在某些情况下.getComputedStyle(),似乎为height元素的属性返回不完整/不正确的值。现在我很担心。是否已知会为其他属性返回不可预测或不正确的值?

背景故事:我一直在使用.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>

4

0 回答 0