如何在 Javascript 中获取对象在页面上的绝对位置? [英] How can I get an object's absolute position on the page in Javascript?

查看:29
本文介绍了如何在 Javascript 中获取对象在页面上的绝对位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Javascript 中获取对象在页面上的绝对 x,y 位置.我该怎么做?

I want to get an object's absolute x,y position on the page in Javascript. How can I do this?

我尝试了 obj.offsetTopobj.offsetLeft,但它们只给出相对于父元素的位置.我想我可以循环并添加父级的偏移量及其父级的偏移量,依此类推,直到我到达没有父级的对象,但似乎应该有更好的方法.谷歌搜索没有出现太多,甚至 SO 网站搜索也没有找到任何东西.

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.

另外,我不能使用 jQuery.

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
    };
};

(方法无耻地从PrototypeJS中盗取;代码风格、变量名和返回值都改了,以保护无辜)

(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)

这篇关于如何在 Javascript 中获取对象在页面上的绝对位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆