Getboundingclientrect: Calculate the offsetleft and offsettop of page elements.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.