首页 > Web开发 > 详细

jquery offsetParent()源码解读

时间:2015-04-19 06:18:03      阅读:259      评论:0      收藏:0      [点我收藏+]
    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相当给力啊,其他的回答明天再看好了,滚回去碎觉。。。)

jquery offsetParent()源码解读

原文:http://www.cnblogs.com/qianlegeqian/p/4438508.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!