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.