【发布时间】:2010-01-21 19:14:53
【问题描述】:
我见过this question,但感觉必须有一个“更干净”的jQuery 方法来执行此操作。我什至不确定这是否真的适用于所有场景。 jQuery有没有办法在不比较尺寸的情况下判断容器是否溢出?
为了澄清,有没有方法可以测试CSS属性overflow: hidden是否已经启动并隐藏内容?
【问题讨论】:
我见过this question,但感觉必须有一个“更干净”的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('<div>');
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;
};
【讨论】:
return (h1 > h2) ? true : false; 是重复的……return h1 > h2; 应该足够了 ;)
没有干净的方法。你可以把它做成两个包装器,外包装器有overflow: hidden,并比较两个包装器的尺寸,但你可能做的任何事情最终都会变得很糟糕。如果该功能确实是必要的,那么您将不得不忍受这些黑客攻击。
【讨论】:
width 检查。在我接受之前,我会让这个运行一下,看看是否有人有实际的解决方案。
我发现的一个简单的解决方案是检测parent() 的scrollWidth:
var totalWidth = $(this).parent()[0].scrollWidth;
0 索引是指父级的“根节点”,从那里获取属性。
【讨论】:
还有另一种解决方案,(这个例子是测试高度是否溢出)它要求溢出的容器是position:relative:
<div id="overflowing-container" style="position:relative">
<div class="children"></div>
<div class="children"></div>
<div class="children"></div>
</div>
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")
}
【讨论】: