如何在 Javascript 中获取对象在页面上的绝对位置?
我想在 Javascript 中获取对象在页面上的绝对 x,y 位置。我该怎么做?
我尝试了 obj.offsetTop 和 obj.offsetLeft,但它们仅给出相对于父元素的位置。我想我可以循环并添加父级的偏移量及其父级的偏移量,依此类推,直到到达没有父级的对象,但似乎应该有更好的方法。谷歌搜索并没有找到太多结果,甚至网站搜索也没有找到任何东西。
另外,我无法使用 jQuery。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(无耻地窃取PrototypeJS的方法;更改代码风格、变量名和返回值以保护无辜者)
(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)
我绝对建议使用 element.getBoundingClientRect()。
https ://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect
这是取自链接的 MDN 站点的浏览器兼容性表:
它受到广泛支持,并且非常易于使用,更不用说它非常快了。以下是 John Resig 的相关文章: http://ejohn.org/blog/getboundingclientrect-is- Awesome/
你可以像这样使用它:
这是一个非常简单的示例:http ://jsbin.com/awisom/2(您可以通过点击右上角的“在 JS Bin 中编辑”来查看和编辑代码)。
或者这是使用 Chrome 控制台的另一个:
注意:
我必须提到
getBoundingClientRect()
方法的width
和height
属性返回值在 Internet Explorer 8 中是未定义
。但它可以在 Chrome 26.x、Firefox 20.x 和 Opera 12.x 中运行。 IE8 中的解决方法:对于width
,您可以减去返回值的 right 和 left 属性,对于height
,您可以减去 Bottom 和 Top 属性 (像这样)。I would definitely suggest using element.getBoundingClientRect().
https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect
Here's a browser compatibility table taken from the linked MDN site:
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:
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:
Note:
I have to mention that the
width
andheight
attributes of thegetBoundingClientRect()
method's return value areundefined
in Internet Explorer 8. It works in Chrome 26.x, Firefox 20.x and Opera 12.x though. Workaround in IE8: forwidth
, you could subtract the return value's right and left attributes, and forheight
, you could subtract bottom and top attributes (like this).