使用jQuery来检测容器溢出?

Jas*_*son 9 css jquery overflow

我已经看过这个问题,但感觉必须有一个"更干净"的jQuery方法来做到这一点.我甚至不确定这是否真的适用于所有场景.有没有办法让jQuery确定容器是否有溢出而不比较维度?

为了澄清,有没有一种方法来测试CSS属性是否overflow: hidden已经启动并隐藏内容?

小智 12

$.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)


小智 5

您可以更改css属性以满足您的需求.

$.fn.hasOverflow = function() {
    $(this).css({ overflow: "auto", display: "table" });
    var h1 = $(this).outerHeight();

    $(this).css({ overflow: "hidden", display: "block" });
    var h2 = $(this).outerHeight();

    return (h1 > h2) ? true : false;
};
Run Code Online (Sandbox Code Playgroud)

  • `return(h1> h2)?true:false;`重复...`return h1> h2;`应该足够了;) (9认同)