offset
The offsetTop and offsetLeft attributes of elements are very useful in all browsers. They give you the coordinate position of your element relative to its parent element.
This code will look up for offsetParent and then add offsetTop and offsetLeft. In the end, no matter where offsetParent is, it will give you the real coordinates of your element on the screen.
Explanation
This code is very simple. First pass in the element to be calculated, and then set the variables curleft and curtop to 0.
function findPos(obj) {
var curleft = curtop = 0;
If the browser supports offsetParent:
if (obj.offsetParent) {
Every time we find a new object, add its offsetTop and offsetLeft to curtop and curleft:
do {
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
Tips: Return the value of '='
Here's the trick:
} while (obj = obj.offsetParent);
This is not an expression error. I don't want to use '==' to compare obj with obj.offsetParent (that doesn't work either, because an element is definitely not equal to its parent).
So I use '=' to pass the value of obj.offsetParent to obj. I have a detailed explanation of this technique here.
Simply return
This loop will end when the element has no offsetParent. When offsetParent exists, offsetLeft will still be added to curleft and offsetTop will be added to curtop.
When looping, we return the coordinates to the program that called this function.
return [curleft,curtop];}
Translation address: http://www.quirksmode.org/js/findpos.html
Please keep the following information for reprinting
Author: Beiyu (tw:@rehawk)
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn