capture mouse position on setInterval() in Javascript

泄露秘密 提交于 2019-11-30 20:11:48

The only time that you can access the event object is during the execution of an event handler. So what you need to do is create an OnMouseMove event on the document and store the mouse coordinates in a globally accessible object. You can then access these values from anywhere else in your script to determine the mouse position.

Here is an example (you're not using jQuery, so this is straight DOM code):

document.onmousemove = function(e) {
    var event = e || window.event;
    window.mouseX = event.clientX;
    window.mouseY = event.clientY;
}

function mousemov() {
    document.getElementById("myDiv").style.left = window.mouseX;
}

window.onload = function() {
    setInterval(mousemov, 1000);
}

I should make the note that clientX and clientY don't take scrolling into account. You'll need to retrieve the scrolling offsets and apply them to the returned values.

well, if you listen to mouse move for the document and save its location, then, whenever you want, e.g. every second in your case you have the latest registered mouse position.

this is a jquery example

$(document).ready(function()
 {
  $().mousemove(function(e)
   {
       window.mouseX = e.pageX;
       window.mouseY = e.pageY;
  });
});

and your mousemove function would be

function mousemov() { 
    document.getElementById("myDiv").style.left = window.mouseX;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!