2011-08-21 21 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

yはclientHeightとscrollHeightを比較することで、以下を試してみてくださいすることを行います、Chamikaの答えのバリエーションがあなたの実際のHTML内にある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); 

、あなたがeasilでき

(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

の内側を持っている:

<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> 

詳細についてはをご覧くださいおよび外部部門。外側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> 
関連する問題