Position code is relatively simple ...
Positionfunction() { if( ! This[0 ] ) { return; } varoffsetParent, offset, elem= This[0], Parentoffset= {top:0, left:0 }; //Fixed elements is offset from window (Parentoffset = {top:0, left:0}, because it's it only offset parent if(Jquery.css (Elem, "position") = = = "fixed" ) { //assume Getboundingclientrect is there while computed position is fixedoffset =Elem.getboundingclientrect (); } Else { //Get *real* offsetParentOffsetParent = This. OffsetParent (); //Get correct offsetsoffset = This. offset (); if(!jquery.nodename (offsetparent[0], "HTML") ) {Parentoffset=Offsetparent.offset (); } //Add offsetParent bordersParentoffset.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 ) }; }
If the current element is fixed positioning, you can use the Getboundingclientrect () method directly to get its position relative to the viewport.
If it is not fixed, then we first need to get our own offset, and then find the nearest location of the parent element, to get the offset of this parent element
Because position asks for the position of the element relative to the nearest positioned parent element
So, you need to get the offset-of the current element based on the offset-of the negative element of the parent element-the margin of the current element.
There is a question is why to exclude margin distance, read a few articles, said is position is similar to the element at the beginning of a positioning element to deal with, so that, indeed can understand the pass, then, at this time Position.left position.top is the equivalent of left and top in CSS?
JQuery position () Source code interpretation