Track mouse speed with JS

前端 未结 5 1890
余生分开走
余生分开走 2020-12-23 19:07

What\'s the best way to track the mouse speed with plain JS/JQuery? I\'d like to track how fast a user moves the mouse in all directions (up/down/left/right).

5条回答
  •  时光说笑
    2020-12-23 19:45

    Sparklines has a nifty example of tracking mouse movement and graphing it. Their code is available in the source of their site starting at line 315.

    Simple and effective.

    Here is the code:

     var mrefreshinterval = 500; // update display every 500ms
     var lastmousex=-1; 
     var lastmousey=-1;
     var lastmousetime;
     var mousetravel = 0;
     $('html').mousemove(function(e) {
         var mousex = e.pageX;
         var mousey = e.pageY;
         if (lastmousex > -1)
             mousetravel += Math.max( Math.abs(mousex-lastmousex), Math.abs(mousey-lastmousey) );
         lastmousex = mousex;
         lastmousey = mousey;
     });
    

提交回复
热议问题