clientWidth和clientHeight报告零,而getBoundingClientRect是正确的 [英] clientWidth and clientHeight report zero while getBoundingClientRect is correct

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

问题描述

在MDN的 Element.clientWidth 说明中说。

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


Element.clientWidth属性是以像素为单位的元素的内部宽度。


此属性会将值四舍五入为整数。如果你需要一个小数值,使用element.getBoundingClientRect()。



除了舍入 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>  

解决方案

从规范( http://www.w3.org/TR/cssom-view/#dom-element-clientwidth


clientWidth属性必须执行以下步骤:



没有关联的CSS布局框或如果CSS布局框内嵌,则返回

...



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

Note: I've since updated MDN according to @potatopeelings answer.

The Element.clientWidth property is the inner width of an element in pixels. It includes padding but not the vertical scrollbar (if present, if rendered), border or margin.

This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect().

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)

The clientWidth attribute must run these steps:

1.If the element has no associated CSS layout box or if the CSS layout box is inline, return zero.
...

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆