【问题标题】:Getting required width of an overflowing span in JS在 JS 中获取溢出跨度的所需宽度
【发布时间】:2014-09-04 01:28:59
【问题描述】:
<div id="wrapper" style="width:50px; overflow:hidden;">
  <span id="innerPart" style="white-space: nowrap; width: auto;">Lorem ipsum...</span>
</div>

你好互联网, 我试图获得 innerPart 需要通过 JS 完全显示的宽度。 尝试使用document.getElementById("innerPart").width;,但它只是返回null

【问题讨论】:

  • 尝试将css:inline-block 分配给该跨度并检查,如果您在尝试 dis 后没有获得宽度,请在此处评论
  • 不工作。我意识到 '.getAttribute("width")' 是错误的函数。但是“.width”也是空的。
  • 应该是.css("width")
  • 我没有使用 jquery atm。我现在就试试。
  • 很遗憾,它也不起作用。

标签: javascript html width


【解决方案1】:

使用document.getElementById("innerPart").offsetWidth

看到这个answer

如果您想要 width 属性,则不要使用 style 属性。例如。 document.getElementById("innerPart").style.width

不同之处在于 offsetWidth 是一个计算属性,它考虑了边框和填充,而 width 没有。您可能会发现 width 为 null,如果您没有专门设置宽度,我假设这是正确的。

【讨论】:

    猜你喜欢
    • 2013-10-16
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2014-10-10
    • 2013-05-18
    • 2010-10-20
    相关资源
    最近更新 更多