<div style="width: 50px;">
<div id="theElement" style="position: relative; left 25px;">textMuchLongerThan50[</div开发者_JAVA技巧>
</div>
document.getElementById("theElement").clientWidth always returns 50, which is width of the parent element, while it is obvious the element's content is much wider
(The element itself actually has this width, but I need to know its "natural" width, i.e. width of its content.)
Experiencing this behaviour in Chrome and IE. If anoyne knew how to determine the actual dimensions of a relatively positioned DIV residing in another DIV with pre-set/limited width...?
You are interested in scrollWidth: Example
This is because it's a block element, and it is actually taking its width from its parent. The text inside it is overflowing outside of its container, but isn't affecting the container's actual width.
You can prove this by adding a border
style to the inner <div>
.
You can cause the element to take its width from the width of the text by changing its display type.
If you set it to display:inline-block;
, it will report the correct width.
And if you add a border
now, you'll notice that it has changed as well.
精彩评论