2013-07-07 42 views
0

是否有方法檢查元素文本是否溢出其容器?例如,我有一個<p>width: 100px。這個元素的文本佔用了105px。我可以看到我的text-overflow: ellipsis被應用,但我也想在我的JS中知道。檢測文本是否溢出

jQuery或普通的js是好的。

+1

見http://stackoverflow.com/questions/2059743/detect-elements-overflow-using-jquery,http://stackoverflow.com/questions/ 143815 /如何確定使用javascript-if-html-element-has-overflowing-content,http://stackoverflow.com/questions/7668636/check-with-jquery-if-div-has-overflowing-分子 – lifetimes

回答

0

你可以做這樣的事情:

/* 
* @param el DOM element or jQuery object 
* @return w width of the text 
*/ 
function getOverflowWidth(el) { 
    var $el = $(el); 
    var span = $el.wrapInner('<span />').find('span'); 
    var w = span.width(); 
    $el.html(span.html()); 
    return w; 
}