jquery offsetParent()源码解读

    offsetParent: function() {
        return this.map(function() {
            var offsetParent = this.offsetParent || docElem;

            while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
                offsetParent = offsetParent.offsetParent;
            }

            return offsetParent || docElem;
        });
    }

代码比较简单,首先它return this.map(function(){}) 所以返回的是一个数组。。。

获取当前元素的offsetParent,如果没有的话就是documentElement

jQuery.nodeName("offsetParent","html")是为了判断当前的offsetParent是否是html,然后jQuery.css( offsetParent, "position") === "static" ) 判断offsetParent是否是static...

但是问题来了,什么时候while为true呢?

( !jQuery.nodeName( offsetParent, "html" )排除了html,但是还有一个body我们不能忽略。

然后我发现。。
console.log(document.getElementById('div').offsetParent);
    console.log($('#div').offsetParent());

原生返回body而jQuery返回html

原因,刚在stackoverflow上问了一下,确实,不管jquery返回html或者body都不重要,反正都是说明当前元素没有一个有定位的祖先元素,而jquery返回html的原因,可能就是想做一下标准化吧。。

(PS~stackoverflow相当给力啊,其他的回答明天再看好了,滚回去碎觉。。。)

原文地址:https://www.cnblogs.com/qianlegeqian/p/4438508.html