clientWidth“说谎”,无法确定元素的实际宽度
<div style="width: 50px;">
<div id="theElement" style="position: relative; left 25px;">textMuchLongerThan50[</div>
</div>
document.getElementById("theElement").clientWidth 总是返回 50,这是父元素的宽度,而很明显元素的内容要宽得多
(元素本身实际上有这个宽度,但我需要知道它的“自然”宽度,即其内容的宽度。)
在 Chrome 和 IE 中体验这种行为。如果有人知道如何确定位于另一个具有预设/有限宽度的 DIV 中的相对定位 DIV 的实际尺寸...?
<div style="width: 50px;">
<div id="theElement" style="position: relative; left 25px;">textMuchLongerThan50[</div>
</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...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您对 scrollWidth 感兴趣:示例
You are interested in scrollWidth: Example
这是因为它是一个块元素,并且它实际上从其父元素获取宽度。它里面的文本溢出到容器之外,但不会影响容器的实际宽度。
您可以通过向内部
添加
border
样式来证明这一点。您可以通过更改元素的显示类型来使元素从文本宽度获取其宽度。
如果将其设置为
display:inline-block;
,它将报告正确的宽度。如果您现在添加
边框
,您会注意到它也发生了变化。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.