如何检测div元素中的溢出?

50

我该如何检测一个 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
你所说的“detect”具体是什么意思?你想要做出什么反应,显示一个滚动条吗? - Pekka
我想在鼠标悬停时调整 div 的大小,如果文本溢出,但我已经解决了这个问题,所以它不是问题的一部分。 - Vladimir Perković
类似的老问题,有很好的答案:https://dev59.com/-nVC5IYBdhLWcg3w7Vxq#143889 - earcam
3个回答

56
你可以通过比较scrollHeight和clientHeight来轻松实现,尝试以下操作:

你可以通过比较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


如果div的溢出规则为'visible',这将无效。这是默认设置。使用Firefox 18。 - Ryan
1
它也没有告诉你哪个具体的div溢出了。 - NoBugs
这个解决方案的问题在于,如果元素被隐藏(或其父级被隐藏),两者都返回0。有什么解决方法吗? - Toni Michel Caubet
如果溢出是可见的,那么问题通常是无意义的。 - undefined

6
一个变化的方法是在您的实际HTML中使用内部和外部Div。 外部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>

4
以下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/


5
不确定这是否是检查方式中最有效或最佳的一种,如果该特定div内有脚本,它将重新运行。 - NoBugs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接