capture mouse position on setInterval() in Javascript

后端 未结 2 1223
小鲜肉
小鲜肉 2021-01-05 07:09

I have a function in javascript that moves one div depending on the mouse position. This function is set on a setInterval() function and executed every second. I need to cap

2条回答
  •  醉酒成梦
    2021-01-05 07:49

    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;
    }
    

提交回复
热议问题