如何获取隐藏溢出的元素的宽度?

How to get the width of an element where the overflow is hidden?

我有一个 button 元素,里面有一个 span 元素,我需要能够获得 span 的实际宽度。

<button id="button"><span>text that is longer than the button width</span></button>

None 我尝试过的方法显示了真实宽度(JSFiddle 示例约为 233px - 这可以通过简单地删除 overflow:hidden css 属性 来自跨度):

https://jsfiddle.net/teatnmza/

跨度的实际宽度与按钮相同,因为您隐藏了任何溢出。

我认为您需要获取 span 的滚动宽度,事实上您已经快完成了:

$("button span")[0].scrollWidth

使用:

$("button span")[0].scrollWidth  // returns 231

updated fiddle

编辑:没看到是乔治先拿到的,所以功劳必须归功于他。