Obtain an HTML element's positon in body coordinates
If I have a nested HTML element called Div1 (a div that sits inside another div & that other div sits inside the body), how can I get Div1's x,y position from the body elements perspective maybe this is called window/screen position of a HTM开发者_如何学JAVAL element)?
Hope this makes sense :)
function getWhere(node, top){
top= top || document.body;
var x= 0, y= 0;
while(node){
y+= node.offsetTop;
x+= node.offsetLeft;
node= node.offsetParent;
if(node== top) break;
}
return [x, y];
}
If you're using jQuery you can use offset to get the position relative to the document.
$(element).offset();
See: http://api.jquery.com/offset
Unfortunately I have no idea how to do this with pure js.
精彩评论