问题
I've seen this question but feel like there has to be a "cleaner" jQuery method of doing this. I'm not even sure if this really works in all scenarios. Is there a way for jQuery to determine if a container has overflow without comparing dimensions?
For clarification, is there a method to test whether the CSS attribute overflow: hidden
has kicked in and is hiding content?
回答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;
};
Example:
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:
You may change the css attributes to fit your needs.
$.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;
};
回答3:
There is no clean method. You could make it two wrappers, the outer wrapper having overflow: hidden
, and comparing the two wrappers' dimensions, but anything you could possibly do would end up being hacky. If the functionality really is necessary, then you'll have to live with the hacks.
回答4:
A simple solution I have found is to detect the scrollWidth
of the parent()
:
var totalWidth = $(this).parent()[0].scrollWidth;
...I think the
0
index is referring to the "root node" of the parent, obtaining the property from there.
回答5:
There exists another solution, (this example tests if the height overflows) it requires the overflowing container to be 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")
}
来源:https://stackoverflow.com/questions/2112106/use-jquery-to-detect-container-overflow