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