Offset
The offsettop and offsetleft two attributes of the elements in all browsers are useful. They will give you the coordinates of the element relative to the parent element.
This code looks up offsetparent, and then adds offsettop and offsetleft. Eventually, no matter where offsetparent is, he will give you the real coordinates of the element on the screen.
Explain
This code is very simple. First pass in the element to be evaluated, then set the variable curleft and curtop to 0.
Copy Code code as follows:
function Findpos (obj) {
var curleft = curtop = 0;
If the browser supports offsetparent:
Copy Code code as follows:
Every time we find a new object, add his offsettop and offsetleft to Curtop and Curleft:
Copy Code code as follows:
do {
Curleft + = Obj.offsetleft;
Curtop + = Obj.offsettop;
Tip: Return the value of ' = '
Here's the trick:
Copy Code code as follows:
while (obj = obj.offsetparent);
This is not an expression error. I don't want to use ' = = ' to compare obj and obj.offsetparent (that's not going to work because an element is definitely not equal to his parent element).
So I use ' = ' to pass the value of Obj.offsetparent to obj. Here I have a detailed explanation of this technique.
Easy to return
This loop ends when the element has no offsetparent. When offsetparent exist, they will still add offsetleft to the Curleft and add offsettop to the curtop.
When looping technology, we return the coordinates to the program that calls the function.
Copy Code code as follows:
return [Curleft,curtop];}
Translation Address: http://www.quirksmode.org/js/findpos.html
Reprint please keep the following information
Author: North Jade (TW: @rehawk)