Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/464.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么.getComputedStyle()似乎是返回元素不正确高度的唯一常用方法?_Javascript_Getcomputedstyle - Fatal编程技术网

Javascript 为什么.getComputedStyle()似乎是返回元素不正确高度的唯一常用方法?

Javascript 为什么.getComputedStyle()似乎是返回元素不正确高度的唯一常用方法?,javascript,getcomputedstyle,Javascript,Getcomputedstyle,问题:在某些情况下。getComputedStyle()似乎为元素的高度属性返回不完整/不正确的值。现在我很担心。是否已知会为其他属性返回不可预测或不正确的值 后台故事:我一直在使用.getComputedStyle(),直到我注意到它返回的元素高度值似乎不正确。所以我用其他几种方法测试了它 在下面的简单测试代码中,所有这些返回400,这是被测试元素的正确高度 .offsetHeight .scrollHeight .clientHeight .getBoundingClientRect().h

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

后台故事:我一直在使用
.getComputedStyle()
,直到我注意到它返回的元素高度值似乎不正确。所以我用其他几种方法测试了它

在下面的简单测试代码中,所有这些返回400,这是被测试元素的正确高度

.offsetHeight

.scrollHeight

.clientHeight

.getBoundingClientRect().height

但是
.getComputedStyle().height
返回300px,即应用填充之前元素的高度

“严格使用”;
window.addEventListener('load',measureDiv)
函数measureDiv(){
console.log('offsetHeight='+document.querySelector('.container').offsetHeight);
console.log('scrollHeight='+document.querySelector('.container').scrollHeight);
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);
}
正文{
保证金:0;
填充:0;
}
.集装箱{
利润率:120像素;
填充:50px;
背景颜色:绿色;
}
.box_1{
填充:20px;
背景颜色:蓝色;
}
.image_容器{}


这在我看来并不错误;
height
CSS属性不包括填充或边框,除非您有
box size:border-box设置。@Pointy-头脑崩溃!我刚刚添加了
框大小:边框框
到类中,并确定它返回了400px。我现在明白了。@Pointy-FYI我刚刚用IE11中的
box size:border-box
测试了它,它仍然报告了300.14px的高度。但是Chrome、Edge和Firefox都报告了正确的高度,我不知道IE为什么会出错;也许IE运行在一种奇怪的兼容性模式或怪癖模式或其他什么模式下,这就把它甩了。根据Analytics.gov的数据,IE11已降至12.9%,但比两年前的52%略低。希望它能在2年后死去并埋葬。我讨厌用两种方式学习东西。