如何衡量文本在Javascript中占用的空间?

时间:2009-02-02 20:57:35

标签: javascript css text layout

在Javascript中,我有一个字符串,我想以某种方式测量在某个元素中需要多少空间(以像素为单位)。

基本上我所拥有的是一个将浮动在其他所有东西之上的元素(如工具提示),我需要通过Javascript手动设置其宽度,因此它将调整为内部文本。
我不能让它自然地“自动生长”,就像内联元素会水平生长以包含它的孩子一样。

在Windows中,有一些API可以执行此操作。有没有办法在Javascript中做同样的事情?
如果没有合适的方式,您认为哪种方法可行? (比如,尝试不同的宽度并检查高度以确保它没有超过某个阈值)。

我可以在JS中硬编码的“像素值”越少,显然越好。

3 个答案:

答案 0 :(得分:6)

答案 1 :(得分:4)

鉴于此HTML <span>text here</span>,您必须读取span的offsetWidth属性,该属性仅在将元素本身添加到DOM 时指定,而不使用使其不可见的样式。从技术上讲,这意味着浏览器必须能够以可视方式加载DOM中的元素,以便能够构造和分配offsetWidth属性。

这样的事情会起作用:

var span = document.createElement("span");
span.appendChild(document.createTextNode("text here"));

span.style = ""; // to make sure the elment doesn't have "display: none" or such
document.body.appendChild(span); // adding it to the DOM

var textWidth = span.offsetWidth;

// be sure to hide or remove the span if you don't need it anymore

答案 2 :(得分:1)

使用JavaScript框架很容易。我在这个例子中使用Prototype

<span id='text' style='border:1px solid #000000;font-size:14px'>hello this is sample text</span>

<script type="text/javascript">
alert($('text').getWidth())
</script>