如何在Javascript中获取对象的绝对位置? [英] How can I get an object's absolute position on the page in Javascript?
问题描述
我尝试过 obj.offsetTop
和 obj.offsetLeft
,但这些只给出相对于父元素的位置。我想我可以循环并添加父项的偏移量及其父对象的偏移量等等,直到我没有父进程的对象,但似乎应该有一个更好的方法。谷歌搜索并没有变得太多,甚至SO搜索都没有找到任何东西。
此外,我不能使用jQuery。
var cumulativeOffset = function(element){
var top = 0,left =
do {
top + = element.offsetTop || 0;
left + = element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top:top,
left:left
};
}; (方法无耻地从PrototypeJS中被盗;代码样式,变量名和返回值改变为保护无辜者)
<
I want to get an object's absolute x,y position on the page in Javascript. How can I do this?
I tried obj.offsetTop
and obj.offsetLeft
, but those only give the position relative to the parent element. I guess I could loop through and add the parent's offset, and its parent's offset, and so on until I get to the object with no parent, but it seems like there should be a better way. Googling didn't turn up much, and even SO site search isn't finding anything.
Also, I can't use jQuery.
var cumulativeOffset = function(element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
};
(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)
这篇关于如何在Javascript中获取对象的绝对位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!