获取文本节点的宽度

时间:2012-08-14 19:35:40

标签: javascript width

一些(JS修改的)HTML可能如下所示:

<div style="width: 50px;">1,234,567</div>

如何检测文本节点是否比容器宽?

1 个答案:

答案 0 :(得分:3)

受到How to detect overflow in div element?的启发:

<!-- Overflowing -->
<div style="width: 50px;">1,234,567</div>

<!-- Not overflowing -->
<div>1,234,567</div>

要检测的JavaScript(没有jQuery):

var divs = document.getElementsByTagName('div');
var i, div, overflowing;

for (i=0; i<divs.length; i++) {
    div = divs[i];
    overflowing = div.offsetWidth < div.scrollWidth;
    console.log(overflowing);
}​

http://jsfiddle.net/mattball/pYj5P/