當我擁有這個css/html時,是否可以檢查錨文本是否溢出?javascript檢查鏈接中的文本錨文本是否溢出
<a href="#" style"overflow:hidden; width:100px; display:block;>
This is a very long text. This is a very long text. This is a very long text.
</a>
使用jQuery或純JavaScript
當我擁有這個css/html時,是否可以檢查錨文本是否溢出?javascript檢查鏈接中的文本錨文本是否溢出
<a href="#" style"overflow:hidden; width:100px; display:block;>
This is a very long text. This is a very long text. This is a very long text.
</a>
使用jQuery或純JavaScript
您可以將文本內容到TMP元素,然後計算其寬度與<a>
寬度進行比較,以檢查內容溢出與否。見下文,
$('a').on('click', function() {
var $tmp = $('<a/>')
.text($(this).text())
.css('display','none')
.appendTo('body');
alert(($tmp.width() > $(this).width())?'Overflows':'Perfectly Inside');
$tmp.remove();
});
我建議:
var as = document.getElementsByTagName('a');
for (var i=0,len=as.length;i<len;i++){
var that = as[i]
w = that.offsetWidth,
w2 = that.scrollWidth;
if (w<w2) {
console.log("This content overran!");
}
}
差不多以上,但下面還增加了一個 '報告' 元素的DOM:
var as = document.getElementsByTagName('a');
for (var i=0,len=as.length;i<len;i++){
var that = as[i],
w = that.offsetWidth,
w2 = that.scrollWidth,
s = document.createElement('span');
if (w<w2) {
var text = document.createTextNode('This content overran the container, a, element by ' + (w2-w) + 'px.');
s.appendChild(text);
that.parentNode.insertBefore(s,that.nextSibling);
}
}
試試這個
<div id="parent" style="overflow:hidden; width:100px;display:block">
<a id="textblock" href="#" style="white-space: nowrap;" >
This
</a>
</div>
<script>
var p=document.getElementById("parent");
var tb=document.getElementById("textblock");
(p.offsetWidth<tb.offsetWidth)?alert('long'):alert('short');
</script>
HTML:
<a id="a1" href="#" style="overflow:hidden; width:100px; height:10px; display:block">
This is a very long text. This is a very long text. This is a very long text.
</a>
<a id="a2" href="#" style="width:100px; height:10px; display:block">
This is a very long text. This is a very long text. This is a very long text.
</a>
JS:
function hasOverflow($el){
return $el.css("overflow")==="hidden" &&
($el.prop("clientWidth") < $el.prop("scrollWidth") ||
$el.prop("clientHeight") < $el.prop("scrollHeight"));
}
console.log(hasOverflow($("#a1"))); //true
console.log(hasOverflow($("#a2"))); //false
如果鏈接太長,你是否想自動剪切?或者只是尋找一種方法來查看文本是否超過了一定的寬度? – Jason 2012-04-18 17:47:46