【问题标题】:Use jQuery to Detect Container Overflow?使用 jQuery 检测容器溢出?
【发布时间】:2010-01-21 19:14:53
【问题描述】:

我见过this question,但感觉必须有一个“更干净”的jQuery 方法来执行此操作。我什至不确定这是否真的适用于所有场景。 jQuery有没有办法在不比较尺寸的情况下判断容器是否溢出?

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

【问题讨论】:

标签: jquery css overflow


【解决方案1】:
$.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;
};

例子:

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');
}

【讨论】:

  • 这假设孩子没有内联,在这种情况下我们可能需要检查所有宽度/高度的总和。
【解决方案2】:

您可以更改 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;
};

【讨论】:

  • return (h1 &gt; h2) ? true : false; 是重复的……return h1 &gt; h2; 应该足够了 ;)
【解决方案3】:

没有干净的方法。你可以把它做成两个包装器,外包装器有overflow: hidden,并比较两个包装器的尺寸,但你可能做的任何事情最终都会变得很糟糕。如果该功能确实是必要的,那么您将不得不忍受这些黑客攻击。

【讨论】:

  • 叹息...我想你是对的。谢谢你的帮助。我实施了一个相当轻松的width 检查。在我接受之前,我会让这个运行一下,看看是否有人有实际的解决方案。
  • 刚遇到这个,想在一个从来没有滚动条的页面上创建一个菜单(即主体“固定”为 100% 宽度/高度,以便我可以将页脚粘贴到底部不重叠内容)。我想检测菜单是否溢出,如果是,则显示一个向下移动的按钮(而不是'糟糕的滚动条,所以它使用 jQuery 平滑地向下滑动)。我猜我也只能忍受这些黑客,除非其他答案可以满足我的需要。无论如何,我开始评论的原因只是说@Jason,我认为这已经运行了很多更多而不是一段时间!
【解决方案4】:


我发现的一个简单的解决方案是检测parent()scrollWidth

var totalWidth = $(this).parent()[0].scrollWidth;



...我认为0 索引是指父级的“根节点”,从那里获取属性。

【讨论】:

    【解决方案5】:

    还有另一种解决方案,(这个例子是测试高度是否溢出)它要求溢出的容器是position:relative

    HTML

    <div id="overflowing-container" style="position:relative">
        <div class="children"></div>
        <div class="children"></div>
        <div class="children"></div>
    </div>
    

    Javascript

         var last = $('.children:last'), container=$('#overflowing-container')
             lastOffsetHeight = container.scrollTop() + last.outerHeight(true) + last.position().top;
    
         if (last[0] && lastOffsetHeight > container[0].getBoundingClientRect().height) {
           console.log("thisContainerOverflows")     
         }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2021-12-12
      相关资源
      最近更新 更多