2011-08-21 147 views
34

如何檢測div元素中的垂直文本溢出?如何檢測div元素溢出?

CSS:

div.rounded { 
    background-color:#FFF; 
    height: 123px; 
    width:200px; 
    font-size:11px; 
    overflow:hidden; 
} 

HTML:

<div id="tempDiv" class="rounded"> 
    Lorem ipsum dolor sit amet, 
    consectetur  adipiscing elit. Phasellus vel quam vestibulum orci blandit laoreet. 
</div> 
+2

你是什麼意思的「檢測」到底是什麼?你想做什麼反應,顯示一個滾動條? –

+0

如果文本溢出,我想調整div在鼠標懸停上的大小,但我已經對它進行了排序,因此它不是問題的一部分。 –

+0

類似的老問題,很好的回答:https://stackoverflow.com/a/143889/573057 – earcam

回答

45

可以easil Ÿ做到這一點scrollHeight屬性與clientHeight比較,請嘗試以下操作:

<script type="text/javascript"> 
function GetContainerSize() 
{ 
    var container = document.getElementById ("tempDiv"); 
    var message = "The width of the contents with padding: " + container.scrollWidth + "px.\n"; 
    message += "The height of the contents with padding: " + container.scrollHeight + "px.\n"; 

    alert (message); 
} 
</script> 

欲瞭解更多信息,請看一看:http://help.dottoro.com/ljbixkkn.php

+0

如果div上的溢出規則是'visible',這是默認的,這不起作用。使用Firefox 18. – Ryan

+0

它不會告訴你什麼特定的div溢出。 – NoBugs

+0

這種解決方案的問題是,如果元素被隱藏(或它的父級)都返回0 ..任何解決方法? –

5

以下的jQuery插件會通知結果。

CSS

#tempDiv{ 
    height:10px; 
    overflow:hidden; 
}​ 

爲了確定寬度溢出,

(function($) { 
    $.fn.isOverflowWidth = function() { 
     return this.each(function() { 
      var el = $(this); 
      if (el.css("overflow") == "hidden") { 
       var text = el.html(); 
       var t = $(this.cloneNode(true)).hide().css('position', 'absolute').css('overflow', 'visible').width('auto').height(el.height()); 
       el.after(t);  
       function width() { 
        return t.width() > el.width(); 
       }; 
       alert(width()); 
      } 
     }); 
    }; 
})(jQuery); 

爲了確定高度溢出,

(function($) { 
    $.fn.isOverflowHeight = function() { 
     return this.each(function() { 
      var el = $(this); 
      if (el.css("overflow") == "hidden") { 
       var text = el.html(); 
       var t = $(this.cloneNode(true)).hide().css('position', 'absolute').css('overflow', 'visible').height('auto').width(el.width()); 
       el.after(t); 

       function height() { 
        return t.height() > el.height(); 
       }; 
       alert(height()); 
      } 
     }); 
    }; 
})(jQuery); 

http://jsfiddle.net/C3hTV/

+2

不知道這是最有效或最好的方法來檢查 - 如果特定的div內有腳本,它會重新運行它 – NoBugs

2

上Chamika的回答一個變化是,在你的實際的HTML,具有內部和外部分部。外部Div將具有隱藏的靜態高度和寬度以及溢出。內部Div只有內容,並會延伸到內容。

然後,您可以比較2個Div的高度和寬度,而無需動態添加任何內容。

<div id="tempDiv" class="rounded"> 
    <div class="content"> 
     Lorem ipsum dolor sit amet, 
     consectetur  adipiscing elit. Phasellus vel quam vestibulum orci blandit laoreet. 
    </div> 
</div>