Javascript 检测文本是否溢出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6406843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect if text has overflown
提问by Brett
How can you detect if text has overflown? For example, the following text is longer than it's div container allows. How can I detect this in javascript?
如何检测文本是否溢出?例如,下面的文本比它的 div 容器允许的要长。如何在javascript中检测到这一点?
<div style="max-width: 100px; white-space:nowrap; overflow: hidden;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit
</div>
回答by Nathan Bell
If you are using jQuery, you can try comparing the div's width to its scrollWidth.
如果您使用 jQuery,您可以尝试将 div 的宽度与其滚动宽度进行比较。
if ($('#div-id')[0].scrollWidth > $('#div-id').innerWidth()) {
//Text has over-flown
}
回答by artnikpro
You can detect whether text will fit beforeyou 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) {
...
}
回答by Flash
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 插件,写得不是很好,但可以正常工作。发布此内容是因为我在任何地方都没有找到适用于此的插件。
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;
}
回答by mVChr
For illustrative purposes let's say your div has id="d"
, then you could do:
出于说明目的,假设您的 div 有id="d"
,那么您可以这样做:
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.
dWider
如果文本溢出,则 var将为 true,否则为 false。