本文介绍了clientWidth和clientHeight报告零,而getBoundingClientRect是正确的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MDN的说明中说。

/stackoverflow.com/users/360067/potatopeelings's\">@potatopeelings 回答。


除了舍入 clientWidth 应该与 getBoundingClientRect()。width 相同。



但是我看到对于许多元素( display 是 inline ?) $ c> clientWidth (和height)为零,而 getBoundingClientRect 返回的值似乎正确。



在stackoverflow上搜索带来一些答案,说这发生在文档处于一个准备状态,但我看到这一直的时间,而不仅仅是当页面加载。



这个行为对我检查的所有浏览器都是一致的,在哪里指定这应该是行为?



示例:

 
 < span id =s> A span< / span>< br /> < button onclick =test()>测试< / button>< hr />< div id =out>< / div>  

解决方案

从规范()


In MDN's description of Element.clientWidth it says.

From this I understand that other than rounding clientWidth should be the same as getBoundingClientRect().width.

However I see that for many elements (where display is inline?) the clientWidth (and height) are zero, while the values returned by getBoundingClientRect seem correct.

Searching on stackoverflow brings some answers saying that this happens before the document is in a ready state but I see this all the time, not just when the page is loading.

This behaviour is consistent for all browsers I checked, where is it specified that this should be the behaviour?

Sample:

function str(name, width, height) {
  return name + ': (' + width + ', ' + height + ')';
}

function test() {
  var s = document.getElementById('s');
  var rect = s.getBoundingClientRect();
  document.getElementById('out').innerHTML =
    str('client', s.clientWidth, s.clientHeight) + '<br/>' +
    str('bounding', rect.width, rect.height);
}
 <span id="s">A span</span><br/> <button onclick="test()">Test</button>
<hr />
<div id="out"></div>

解决方案

From the spec (http://www.w3.org/TR/cssom-view/#dom-element-clientwidth)

这篇关于clientWidth和clientHeight报告零,而getBoundingClientRect是正确的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 23:21