使用jQuery检测容器溢出?

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

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

 $.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('
'); while($content.hasOverflow()){ var size = parseFloat($content.css('font-size'), 10); size -= 1; $content.css('font-size', size + 'px'); }

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

没有干净的方法。 你可以使它成为两个包装器,外包装有overflow: hidden ,并比较两个包装器的尺寸,但你可能做的任何事情最终都会变成黑客。 如果function真的是必要的,那么你将不得不忍受黑客攻击。

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

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


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

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

HTML

 

使用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") }