javascript-如何检测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>
Vladimir Perković asked 2020-08-11T21:17:34Z
3个解决方案
49 votes

您可以通过将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]

BlackDivine answered 2020-08-11T21:17:44Z
5 votes

以下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://JS fiddle.net/C3和TV/]

Chamika Sandamal answered 2020-08-11T21:18:21Z
5 votes

Chamika答案的一种变化是,在您的实际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>
Josh Russo answered 2020-08-11T21:19:23Z
translate from https://stackoverflow.com:/questions/7138772/how-to-detect-overflow-in-div-element