onMouseMove 获取鼠标位置
在 Javascript 中,在 onMouseMove 的 Javascript 事件处理程序中,如何获取相对于页面顶部的 x、y 坐标中的鼠标位置?
In Javascript, within the Javascript event handler for onMouseMove how do I get the mouse position in x, y coordinates relative to the top of the page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你可以使用 jQuery,那么 这 将会有所帮助:
这里是纯 javascript 示例:
if you can use jQuery, then this will help:
here is pure javascript only example:
这已经在所有浏览器中经过尝试并有效:
现在您可以在如下事件中使用它:
注意: 上面的函数将返回相对于视口的鼠标坐标,该坐标不受滚动的影响。如果您想获取包括滚动的坐标,请使用以下函数。
This is tried and works in all browsers:
Now you can use it in an event like this:
NOTE: The above function will return the mouse co-ordinates relative to the viewport, which is not affected by scroll. If you want to get co-ordinates including scroll, then use the below function.
仅使用 d3.js 来查找鼠标坐标可能有点过分,但它们有一个非常有用的函数,称为 <代码>d3.mouse(*容器*)。下面是执行您想要执行的操作的示例:
在上述情况下,x 坐标将为坐标[0],y 坐标将为坐标[1]< /代码>。这非常方便,因为您可以通过将
'html'
与标签(例如'body'
)交换来获取相对于任何您想要的容器的鼠标坐标,class名称(例如'.class_name'
)或id(例如'#element_id'
)。It might be a bit overkill to use d3.js just for finding mouse coordinates, but they have a very useful function called
d3.mouse(*container*)
. Below is an example of doing what you want to do:In the above case, the x-coordinate would be
coordinates[0]
, and the y-coordinate would becoordinates[1]
. This is extremely handy, because you can get the mouse coordinates with respect to any container you want to by exchanging'html'
with the tag (e.g.'body'
), class name (e.g.'.class_name'
), or id (e.g.'#element_id'
).特别是对于 mousemove 事件,它会快速而激烈地触发,最好在使用它们之前减少处理程序 -
document.ondblclick=function(e){alert(whereAt(e))};
Especially with mousemove events, that fire fast and furious, its good to pare down the handlers before you use them-
document.ondblclick=function(e){alert(whereAt(e))};