检测文本是否溢出

如何检测文本是否溢出?例如,下面的文本比它的 div 容器允许的长。我如何在 javascript 中检测到这一点?

<div style="max-width: 100px; white-space:nowrap; overflow: hidden;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit
</div>
103347 次浏览

If you are using jQuery, you can try comparing the div's width to its scrollWidth.

if ($('#div-id')[0].scrollWidth >  $('#div-id').innerWidth()) {
//Text has over-flown
}

For illustrative purposes let's say your div has id="d", then you could do:

var d = document.getElementById('d'),
dWider;
d.style.maxWidth = '9999em';
d.style.overflow = 'visible';
dWider = d.offsetWidth > 100;
d.style.maxWidth = '100px';
d.style.overflow = 'hidden';

Then the var dWider will be true if the text overflows and false if it doesn't.

jQuery plugin for checking if text has overflown, not written very well, but works as it suppose to be working. Posting this because I didn't find a working plugin for this anywhere.

jQuery.fn.hasOverflown = function () {
var res;
var cont = $('<div>'+this.text()+'</div>').css("display", "table")
.css("z-index", "-1").css("position", "absolute")
.css("font-family", this.css("font-family"))
.css("font-size", this.css("font-size"))
.css("font-weight", this.css("font-weight")).appendTo('body');
res = (cont.width()>this.width());
cont.remove();
return res;
}

You can detect whether text will fit before you display the element. So you can use this function which doesn't require the element to be on screen.

function textWidth(text, fontProp) {
var tag = document.createElement('div')
tag.style.position = 'absolute'
tag.style.left = '-99in'
tag.style.whiteSpace = 'nowrap'
tag.style.font = fontProp
tag.innerHTML = text


document.body.appendChild(tag)
var result = tag.clientWidth
document.body.removeChild(tag)
return result;
}

Usage:

if (textWidth('Text', 'bold 13px Verdana') > elementWidth) {
...
}