In javascript, within the javascript event hander for onMouseMove how do I get the mouse position in x, y corrdinates relative to the top of the page?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
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:
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))};
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'
).