我在我的HTML文档中有几个带有特定CSS类的
元素,并且想要获取这些元素的x、y位置,谢谢。
使用getBoundingClientRect
函数:
例如:
var div = document.getElementById("yourDiv");
var rect = div.getBoundingClientRect();
alert("Coordinates: " + rect.left + "px, " + rect.top + "px");
请记住,getBoundingClientRect
返回的是相对于当前视口的坐标,这意味着如果你想知道相对于document.body
的坐标,你需要添加水平和垂直滚动量(document.documentElement.scrollLeft
或者document.body.scrollLeft
适用于Firefox,当然还有.scrollTop
)。
如果我理解正确,您想要做到这一点 http://www.quirksmode.org/js/findpos.html
getBoundingClientRect
是一个很好的工具,并且被所有主流浏览器支持。它真的可以简化操作。并不是说旧的quirksmode.org代码不再起作用了...只是它更慢一些。 - MaxArt# first tag link of this page
document.getElementsByClassName('post-taglist')[0].children[0].getClientRects()[0]
# question div
document.getElementById('question').getClientRects()[0]
使用它,您可以访问右侧、顶部、高度、宽度、左侧和底部属性。