1

当我有这个 css/html 时,是否可以检查锚文本是否溢出?

<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

4

4 回答 4

2

您可以将文本内容分配给 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();
});
于 2012-04-18T17:45:59.873 回答
0

我建议:

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!");
    }
}​

JS 小提琴演示


与上面差不多,但下面也向 DOM 添加了一个 'reporting' 元素:

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);
    }
}​

JS 小提琴演示

于 2012-04-18T17:51:42.010 回答
0

试试这个

<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>​
于 2012-04-18T18:11:45.890 回答
0

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

演示

于 2012-04-18T18:23:30.550 回答