使用jquery检测元素溢出

Pra*_*sad 34 jquery

CSS:

 .blue
    {
     width:200px;
     height:200px;
     background-color:blue;
     color:#000000;
     overflow:auto;
    }
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

function addChar() {
    $('.blue').append('some text  ');
}
Run Code Online (Sandbox Code Playgroud)

HTML:

<div id='blue1' class="blue"></div><br />
<a href='javascript:void(0)' onclick='addChar()'>Add</a>
Run Code Online (Sandbox Code Playgroud)

div id='blue1'overflow属性设置为auto.我想在发生溢出时检测溢出.

Pra*_*sad 42

$.fn.HasScrollBar = function() {
    //note: clientHeight= height of holder
    //scrollHeight= we have content till this height
    var _elm = $(this)[0];
    var _hasScrollBar = false; 
    if ((_elm.clientHeight < _elm.scrollHeight) || (_elm.clientWidth < _elm.scrollWidth)) {
        _hasScrollBar = true;
    }
    return _hasScrollBar;
}
Run Code Online (Sandbox Code Playgroud)

///这是我的解决方案

  • 我在这里发布这个问题后找到了解决方案!! (13认同)

小智 20

$.fn.hasOverflow = function() {
    var $this = $(this);
    var $children = $this.find('*');
    var len = $children.length;

    if (len) {
        var maxWidth = 0;
        var maxHeight = 0
        $children.map(function(){
            maxWidth = Math.max(maxWidth, $(this).outerWidth(true));
            maxHeight = Math.max(maxHeight, $(this).outerHeight(true));
        });

        return maxWidth > $this.width() || maxHeight > $this.height();
    }

    return false;
};
Run Code Online (Sandbox Code Playgroud)

例:

var $content = $('#content').children().wrapAll('<div>');
while($content.hasOverflow()){
    var size = parseFloat($content.css('font-size'), 10);
    size -= 1;
    $content.css('font-size', size + 'px');
}
Run Code Online (Sandbox Code Playgroud)


Noy*_*oyo 16

针对具体问题的单线解决方案:

var elt, hasOverflow = (elt = $('#blue1')).innerWidth() > elt[0].scrollWidth;
Run Code Online (Sandbox Code Playgroud)

只是想打高尔夫球.:]

(注意:这仅适用于水平溢出检测;添加垂直溢出检测也很简单.)