鼠标停止或改变方向时获取鼠标坐标

时间:2012-08-27 09:47:32

标签: javascript jquery mousemove

我用简单的代码获得鼠标位置:

$("#container").mousemove( function(e) {

    client_x = e.pageX;
    client_y = e.pageY;

        // save coordinates

});

但是当鼠标改变方向时我只需要开始和停止坐标+坐标,所以我可以“复制”鼠标移动。

我想我需要某种计时器来查看鼠标是否停留了一段时间?

1 个答案:

答案 0 :(得分:1)

var timer, timer2 = 0, client_x, client_y; //I made them global since it's easier
$("#container").mousemove( function(e) {
  clearTimeout(timer);
  client_x = e.pageX;
  client_y = e.pageY;
  if((new Date()).getTime() > timer2 + 2000) {
    timer2 = (new Date()).getTime(); //just in case this event handler gets called again before the timer runs doCopy
    setTimeout(doCopy, 1); //run "outside" the event handler (since it's not good for an event handler to take a long time
  } else {
    timer = setTimeout(doCopy, 1000);
  }
});

function doCopy() {
  timer2 = (new Date()).getTime();
  .....
}

这是不断设置和清除计时器。如果鼠标停止1秒钟,则会触发doCopy()功能。