zoukankan      html  css  js  c++  java
  • jQuery position() 源码解读

    position的代码比较简单。。。

        position: function() {
            if ( !this[ 0 ] ) {
                return;
            }
    
            var offsetParent, offset,
                elem = this[ 0 ],
                parentOffset = { top: 0, left: 0 };
    
            // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
            if ( jQuery.css( elem, "position" ) === "fixed" ) {
                // Assume getBoundingClientRect is there when computed position is fixed
                offset = elem.getBoundingClientRect();
    
            } else {
                // Get *real* offsetParent
                offsetParent = this.offsetParent();
    
                // Get correct offsets
                offset = this.offset();
                if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
                    parentOffset = offsetParent.offset();
                }
    
                // Add offsetParent borders
                parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
                parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
            }
    
            // Subtract parent offsets and element margins
            return {
                top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
                left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
            };
        }

    如果当前元素是固定定位,可以直接使用getBoundingClientRect()方法获取其相对于视口的位置。

    如果不是固定定位,这时候我们首先需要获取自身的offset,然后找到最近的有定位的父元素,来获取这个父元素的offset

    因为position求的是元素相对于最近的有定位的父元素的位置

    所以,你需要根据当前元素的offset-父元素的offset-负元素的边框-当前元素的外边距来获取

    有一个疑问就是为什么要去排除margin的距离,看了几篇文章,说是position是类似把元素当初一个有定位的元素来处理,这样的话,确实可以理解的通,那么,此时position.left position.top 就相当于css中的left 和 top ?

  • 相关阅读:
    ionic环境搭建
    C# Enum Type
    【IOS】3. OC 类声明和实现
    【IOS】2.基础
    【IOS】1.学前准备
    win8, VS2013 .NET 4.5在哪找svcutil.exe?
    【你吐吧c#每日学习】11.10 C# Data Type conversion
    【你吐吧c#每日学习】10.30 C#Nullable Types
    【你吐吧c#每日学习】10.29 C#字符串类型&Common operators
    给三个int,判断是否可构成三角形算法
  • 原文地址:https://www.cnblogs.com/qianlegeqian/p/4460035.html
Copyright © 2011-2022 走看看