[Record] JavaScript obtains the DOM element position

Source: Internet
Author: User

Sometimes the project uses js to get the element location to locate the element, which is actually very simple.

The definition of Dom is as follows:

 

You can use

  • Htmlelement. offsetleft
  • Htmlelement. offsettop

However, the values stored in these two attributes are not the absolute position of the element relative to the entire browser canvas, but the relative position relative to the position of its parent element, that is to say, the two values are calculated based on the (0, 0) Point in the upper left corner of the parent element. Therefore, to obtain her absolute position, we must obtain the position of its parent element in sequence, and then obtain the offersetleft and offersettop of its parent element, always recursion to the horizontal and vertical distance of the entire canvas of the browser, for example

/* Obtain the ordinate of an element */
Function gettop (e ){
VaR offset = E. offsettop;
If (E. offsetparent! = NULL ){
Offset + = gettop (E. offsetparent );
}
Return offset;
}
/* Obtain the abscissa of an element */
Function getleft (e ){
VaR offset = E. offsetleft;
If (E. offsetparent! = NULL ){
Offset + = getleft (E. offsetparent );
}
Return offset;
}

Obtain the absolute position of an element. It is based on the element left and top of the browser. We Can slightly change it to get a method.

Function getelempos (OBJ ){
VaR Pos = {"TOP": 0, "Left": 0 };
If (obj. offsetparent ){
While (obj. offsetparent ){
POs. Top + = obj. offsettop;
POs. Left + = obj. offsetleft;
OBJ = obj. offsetparent;
}
} Else if (obj. X ){
POs. Left + = obj. X;
} Else if (obj. X ){
POs. Top + = obj. Y;
}
Return {X: pos. Left, Y: pos. Top };

}

View demo-Example

Click here to see my location

Note: The elements are compatible with chrome, Firefox, ie8.0 +, and safari.

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.