zoukankan      html  css  js  c++  java
  • 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相当给力啊,其他的回答明天再看好了,滚回去碎觉。。。)

  • 相关阅读:
    java基础知识
    21-树形结构菜单之封装递归组件
    05-写vue中的一些小细节
    20-Mock拦截ajax请求,模拟数据
    19-count-to数字滚动组件封装
    18-简单封装axios
    04-Vscode-setting设置
    17-vue给有需要的路由设置title
    03-vuecli中的.editorconfig文件
    06-npm下载依赖存放位置修改
  • 原文地址:https://www.cnblogs.com/qianlegeqian/p/4438508.html
Copyright © 2011-2022 走看看