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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…