Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

javascript - clientWidth and clientHeight report zero while getBoundingClientRect is correct

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.
...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...