1

I am trying out the following code:

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("span").click(function(){
    alert($(this).offsetParent().length);
  });
});
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<p><span>Click me away!</span></p>
<p>Click me too!</p>
</body>
</html>

From the jQuery documentation, offsetParent() is supposed to return the closest positioned parent, positioned meaning one with position defined explicitly as 'static,absoluteorrelative`. here, none is declared for any element, yet the alert pops up 1. How come?

4

1 回答 1

4

首先,让我们看看返回结果:

[html, prevObject: jQuery.fn.jQuery.init[1], context: span, jquery: "1.9.0", constructor: function, init: function…]

所以$(span).offsetParent()你得到了HTML元素。

现在让我们看一下 的实现offsetParent

offsetParent: function() {
    return this.map(function() {
        var offsetParent = this.offsetParent || document.documentElement;
        while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
            offsetParent = offsetParent.offsetParent;
        }
        return offsetParent || document.documentElement;
    });
}

从上面的代码中我们看到,如果我们没有定位父元素,则offsetParent返回该HTML元素。

唯一不好的是,当我查看不存在的文档时。

要检查是否真的有offsetParent你可以使用:

document.getElementsByTagName('html')[0] === $(elem).offsetParent()[0]

于 2013-01-22T08:09:00.637 回答