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

标签 javascript jquery mousemove

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

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

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

        // save coordinates

});

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

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

最佳答案

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() 函数就会被触发。

关于javascript - 当鼠标停止或改变方向时获取鼠标坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12139651/

相关文章:

javascript - 如何为 JavaScript 选项卡创建 HTML 书签 anchor

javascript - "props.children"如何在 React 组件上工作?

javascript - javascript 中的删除按钮和 readURL

javascript - 防止提交空白输入和文本区域

javascript - 避免多次点击 AngularJS 中的按钮

javascript - 每次按键时都会起作用

javascript - 在mousemove上平移指定范围内的div位置

javascript - 如何使用 Javascript 和/或 jQuery 从父窗口访问 iframe 文档事件鼠标位置

javascript - jQuery 隐藏/显示偏移问题

javascript - 通过将鼠标悬停在 D3.js 中的节点上来显示多个节点的工具提示