在JS中,如何在DIV中获取鼠标坐标?

时间:2021-12-09 20:32:20

In JS, how can I get the mouse coordinates inside a DIV? if I use event.pageX, it will only work if the DIV is at the top left corner of the page... otherwise, I have to know the position of the DIV in the page and subtract event.pageX from that. This is hard to do when I generate the DIVs dynamically since I have to keep track of the position of each DIV. Any ideas?

在JS中,如何在DIV中获取鼠标坐标?如果我使用event.pageX,它只有在DIV位于页面的左上角时才有效...否则,我必须知道页面中DIV的位置并从中减去event.pageX。当我动态生成DIV时,这很难做到,因为我必须跟踪每个DIV的位置。有任何想法吗?


It seems like event.layerX and event.layerY works find in FF if I define the DIV with an absolute position. Here is a short example:

如果我用绝对位置定义DIV,似乎event.layerX和event.layerY可以在FF中找到。这是一个简短的例子:

http://www.zangware.com/divpos.html

But in IE, event.layerX/Y is undefined inside the DIV. Any ideas?

但在IE中,event.layerX / Y在DIV中未定义。有任何想法吗?

2 个解决方案

#1


It sounds to me like you answered your own question. I'm not aware of any shortcuts for finding the cursor position from within a div simpler than subtracting the x and y coordinates of the mouse from the x and y coordinates of the upper left corner of the div. Just make sure you cache the location of the div as it changes to avoid a DOM lookup each time the mouse cursor moves.

听起来像你回答了自己的问题。我不知道从div中找到光标位置的任何快捷方式比从div的左上角的x和y坐标减去鼠标的x和y坐标更简单。只需确保在更改div时缓存div的位置,以避免每次鼠标光标移动时进行DOM查找。

#2


It's not too hard. Each element has an offsetTop and offsetLeft property. You can use that with current mouse position to figure out the relative position.

这不是太难。每个元素都有一个offsetTop和offsetLeft属性。您可以使用当前鼠标位置来确定相对位置。

#1


It sounds to me like you answered your own question. I'm not aware of any shortcuts for finding the cursor position from within a div simpler than subtracting the x and y coordinates of the mouse from the x and y coordinates of the upper left corner of the div. Just make sure you cache the location of the div as it changes to avoid a DOM lookup each time the mouse cursor moves.

听起来像你回答了自己的问题。我不知道从div中找到光标位置的任何快捷方式比从div的左上角的x和y坐标减去鼠标的x和y坐标更简单。只需确保在更改div时缓存div的位置,以避免每次鼠标光标移动时进行DOM查找。

#2


It's not too hard. Each element has an offsetTop and offsetLeft property. You can use that with current mouse position to figure out the relative position.

这不是太难。每个元素都有一个offsetTop和offsetLeft属性。您可以使用当前鼠标位置来确定相对位置。