如何在 Javascript 中获得对象在页面上的绝对位置?

我想在 Javascript 中得到一个对象在页面上的绝对 x,y 位置,我该怎么做呢?

我尝试了 obj.offsetTopobj.offsetLeft,但它们只给出相对于父元素的位置。我想我可以循环并添加父类的偏移量,和它的父类的偏移量,以此类推,直到我得到没有父类的对象,但似乎应该有更好的方法。谷歌搜索没有得到什么结果,即使这样,网站搜索也没有找到任何东西。

另外,我不能使用 jQuery。

174526 次浏览
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)

I would definitely suggest using element.getBoundingClientRect().

https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect

Summary

Returns a text rectangle object that encloses a group of text rectangles.

Syntax

var rectObject = object.getBoundingClientRect();

Returns

The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

Here's a browser compatibility table taken from the linked MDN site:

+---------------+--------+-----------------+-------------------+-------+--------+
|    Feature    | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
+---------------+--------+-----------------+-------------------+-------+--------+
| Basic support | 1.0    | 3.0 (1.9)       | 4.0               | (Yes) | 4.0    |
+---------------+--------+-----------------+-------------------+-------+--------+

It's widely supported, and is really easy to use, not to mention that it's really fast. Here's a related article from John Resig: http://ejohn.org/blog/getboundingclientrect-is-awesome/

You can use it like this:

var logo = document.getElementById('hlogo');
var logoTextRectangle = logo.getBoundingClientRect();


console.log("logo's left pos.:", logoTextRectangle.left);
console.log("logo's right pos.:", logoTextRectangle.right);

Here's a really simple example: http://jsbin.com/awisom/2 (you can view and edit the code by clicking "Edit in JS Bin" in the upper right corner).

Or here's another one using Chrome's console: Using element.getBoundingClientRect() in Chrome

Note:

I have to mention that the width and height attributes of the getBoundingClientRect() method's return value are undefined in Internet Explorer 8. It works in Chrome 26.x, Firefox 20.x and Opera 12.x though. Workaround in IE8: for width, you could subtract the return value's right and left attributes, and for height, you could subtract bottom and top attributes (like this).