元素的真实宽度

时间:2015-09-16 15:23:10

标签: javascript html

我有一个非常广泛的<p>元素nowrap,它超出了可见区域。我正试图找到它的宽度。我相信clientWidthoffsetWidth只给我可见区域(在Firefox和Chrome中),因为当我调整窗口大小使其变窄时,返回的值会变小。

我正在考虑以编程方式获取字体和大小,并试图以某种方式计算宽度。我不希望在以后更改字体外观或大小时使用字体外观和大小的硬编码值。

如何使用兼容浏览器的javascript找到段落的宽度?我更喜欢javascript,因为我对jquery一无所知。什么都没有。

<p id="Long" style="white-space:nowrap;">Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string Some super huge string
</p>
<script>
var w = document.getElementById("Long");
document.write(w.offsetWidth); //doesn't work
document.write(w.clientWidth); //doesn't work
</script>

1 个答案:

答案 0 :(得分:5)

document.getElementById('Long').scrollWidth