2012-06-01 113 views

回答

18

使用getBoundingClientRecthttp://ejohn.org/blog/getboundingclientrect-is-awesome/

例如:

var div = document.getElementById("yourDiv"); 
var rect = div.getBoundingClientRect(); 
alert("Coordinates: " + rect.left + "px, " + rect.top + "px"); 

记住getBoundingClientRect给出相对于当前视,这意味着坐标如果你想知道的相对坐标document.body,您必须添加水平和垂直滚动量(Firefox的document.documentElement.scrollLeftdocument.body.scrollLeft,以及当然是210)。

1

如果我明白了,你想这样做http://www.quirksmode.org/js/findpos.html

+0

啊,是的。如果您想要支持较老的客户,请阅读好文章。但是,该页面需要更新。 – MaxArt

+0

真的吗?你有什么机会可以解释那里失踪的? – Jakub

+1

正如我在我的回答中指出的那样,'getBoundingClientRect'是一个很好的工具,并且受所有主流浏览器的支持。它真的简化了事情。不是旧的quirksmode.org代码不再工作......它只是慢了点。 – MaxArt

1

例子波纹管展示了如何检索一个HTML元素

# first tag link of this page 
document.getElementsByClassName('post-taglist')[0].children[0].getClientRects()[0] 
# question div 
document.getElementById('question').getClientRects()[0] 

有了它,你必须查看在右,上,高度ClientRect,宽度,左侧和底部属性。

+0

'getClientRects'太过分了,你不需要知道所有这些。获得所有反思的主要原因是如果你想知道文本行的位置和大小。 NM。 – MaxArt

+0

NM。错过了MaxArt在别处写的东西。 –