如何使用javascript捕获html元素的x,y位置 [英] How to grab the x, y position of html elements with javascript

查看:80
本文介绍了如何使用javascript捕获html元素的x,y位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在html文档中有一些具有某些CSS类的div元素,并想获得这些元素的x,y位置,请先感谢。

I have in my html document several div elements with certain css class and want to get x, y position of those elements, thanks in advance.

推荐答案

使用 getBoundingClientRect
http://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.scrollLeft document.body.scrollLeft 。 scrollTop 当然。)

Remember that getBoundingClientRect gives the coordinates relative to the current viewport, which means that if you want to know the coordinates relative to the document.body, you have to add the horizontal and vertical scroll amounts (document.documentElement.scrollLeft or document.body.scrollLeft for Firefox, and .scrollTop of course).

这篇关于如何使用javascript捕获html元素的x,y位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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