This is a very popular method on the Internet. When frameworks are not used:
Function Getoffsetposition (element ){
VaR Postop = 0 , Posleft = 0 ;
Do {
Postop + = Element. offsettop | 0 ;
Posleft + = Element. offsetleft | 0 ;
Element = Element. offsetparent;
} While (Element );
Return [Posleft, postop];
}
The offsettop value of some elements in Firefox is incorrect. repeated tests show that it is related to the positioning method of its parent element. The parent element is located with fixed, and the obtained offsettop does not contain the value of documentelement. scrolltop. If the documentelement has the getboundingclientrect method, it uses getboundingclientrect to calculate the offset. To get the exact offset, you need to consider whether the element is the position of the table cell and the parent element.
Ff3.5 IE6 and later safari opera chrome support the getboundingclientrect method. If the compatibility requirement is not high, you can use the followingCode
VaR Getoffsetposition = Function (ELEM ){
If ( ! ELEM) Return {Left: 0 , Top: 0 };
VaR Top = 0 , Left = 0 ;
If ( " Getboundingclientrect " In Document.doc umentelement ){
// Jquery Method
VaR Box = ELEM. getboundingclientrect (),
Doc = ELEM. ownerdocument,
Body = Doc. Body,
Docelem = Doc.doc umentelement,
Clienttop = Docelem. clienttop | Body. clienttop | 0 ,
Clientleft = Docelem. clientleft | Body. clientleft | 0 ,
Top = Box. Top + (Self. pageyoffset | Docelem && Docelem. scrolltop | Body. scrolltop) - Clienttop,
Left = Box. Left + (Self. pagexoffset | Docelem && Docelem. scrollleft | Body. scrollleft) - Clientleft;
} Else {
Do {
Top + = ELEM. offsettop | 0 ;
Left + = ELEM. offsetleft | 0 ;
ELEM = ELEM. offsetparent;
} While (ELEM );
}
Return {Left: left, top: Top };
}
The clienttop clientleft value must be subtracted from the calculation. Otherwise, the difference may be several pixels.