admin管理员组

文章数量:1320670

A bit of (JS-modified) HTML might look like this:

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

How do I detect if the text node is wider than the container?

A bit of (JS-modified) HTML might look like this:

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

How do I detect if the text node is wider than the container?

Share Improve this question asked Aug 14, 2012 at 19:35 Niet the Dark AbsolNiet the Dark Absol 325k85 gold badges474 silver badges599 bronze badges 6
  • I'd guess it'll involve cloning the text node, and dropping it into a container that doesn't have a fixed width, or if you can change the markup, wrap the text content in a <span>, and use the width of that instead. – user1106925 Commented Aug 14, 2012 at 19:39
  • possible duplicate of How to detect overflow in div element?. Just use scrollWidth instead of scrollHeight – Matt Ball Commented Aug 14, 2012 at 19:39
  • @MattBall That seems useful, but I don't have hidden overflow on the element. Will I have to add that, or will it work without an overflow setting? – Niet the Dark Absol Commented Aug 14, 2012 at 19:52
  • It works without overflow: hidden. jsfiddle/mattball/pYj5P – Matt Ball Commented Aug 14, 2012 at 20:08
  • Oh, well that's excellent. If you could make that an answer I'll gladly Accept it. – Niet the Dark Absol Commented Aug 14, 2012 at 20:17
 |  Show 1 more ment

1 Answer 1

Reset to default 7

As inspired by How to detect overflow in div element?:

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

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

JavaScript (no jQuery) to detect:

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/mattball/pYj5P/

本文标签: javascriptGetting the width of a text nodeStack Overflow