Rewrote .offsetParent() to work against the full jQuery set, added tests. Fixes #4922.

This commit is contained in:
John Resig 2009-07-19 13:04:18 +00:00
parent f0681d98fe
commit a3b8ac413f
2 changed files with 33 additions and 6 deletions

View file

@ -147,11 +147,13 @@ jQuery.fn.extend({
}, },
offsetParent: function() { offsetParent: function() {
var offsetParent = this[0].offsetParent || document.body; return this.map(function(){
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') === 'static') ) { while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') === 'static') ) {
offsetParent = offsetParent.offsetParent; offsetParent = offsetParent.offsetParent;
} }
return jQuery( offsetParent ); return offsetParent;
});
} }
}); });

View file

@ -145,7 +145,32 @@ testoffset("body", function( jQuery ) {
equals( jQuery('body').offset().left, 1, "jQuery('#body').offset().left" ); equals( jQuery('body').offset().left, 1, "jQuery('#body').offset().left" );
}); });
test("offsetParent", function(){
expect(11);
var body = jQuery("body").offsetParent();
equals( body.length, 1, "Only one offsetParent found." );
equals( body[0], document.body, "The body is its own offsetParent." );
var header = jQuery("#header").offsetParent();
equals( header.length, 1, "Only one offsetParent found." );
equals( header[0], document.body, "The body is the offsetParent." );
var div = jQuery("#nothiddendivchild").offsetParent();
equals( div.length, 1, "Only one offsetParent found." );
equals( div[0], document.body, "The body is the offsetParent." );
jQuery("#nothiddendiv").css("position", "relative");
div = jQuery("#nothiddendivchild").offsetParent();
equals( div.length, 1, "Only one offsetParent found." );
equals( div[0], jQuery("#nothiddendiv")[0], "The div is the offsetParent." );
div = jQuery("body, #nothiddendivchild").offsetParent();
equals( div.length, 2, "Two offsetParent found." );
equals( div[0], document.body, "The body is the offsetParent." );
equals( div[1], jQuery("#nothiddendiv")[0], "The div is the offsetParent." );
});
function testoffset(name, fn) { function testoffset(name, fn) {