javascript 在没有 JQuery 的情况下检测鼠标移动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13206042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:04:37  来源:igfitidea点击:

Detecting Mouse Movement Without JQuery

javascriptmouse

提问by mark cassaday

I'm looking for a small piece of javascript that will check for mouse movement and in the event it does execute a function. I'm looking to do this without jqueryand preferably compatible with most modern browsers. I have this small script which detects when the mouse isn't moving:

我正在寻找一小段 javascript 来检查鼠标移动,如果它确实执行了一个函数。我希望在没有 jquery 的情况下执行此操作并且最好与大多数现代浏览器兼容。我有这个小脚本可以检测鼠标何时不移动:

<script>
document.onmousemove = (function() {
  var onmousestop = function() {
    /* do stuff */
  }, thread;

  return function() {
    clearTimeout(thread);
    thread = setTimeout(onmousestop, 500);
  };
})();
</script>

I'm hoping things can be edited into firing the do stuff when the mouse is moved for the first time after loading the script? Any help? Thanks

我希望在加载脚本后第一次移动鼠标时,可以将事情编辑为触发执行操作?有什么帮助吗?谢谢

回答by user123444555621

The problem with Amit's solutionis that it removes any existing mousemove listeners. Also, it doesn't clean up when the mouse is first moved, and thus creates unnecessary overhead.

Amit 解决方案的问题在于它删除了所有现有的 mousemove 侦听器。此外,当鼠标第一次移动时它不会清理,因此会产生不必要的开销。

This is the clean way of doing it:

这是这样做的干净方式:

var myListener = function () {
    document.removeEventListener('mousemove', myListener, false);
    // do stuff
};

document.addEventListener('mousemove', myListener, false);

See it in action: http://jsfiddle.net/JQBmA/

看到它在行动:http: //jsfiddle.net/JQBmA/

If you need to support older IEs, you can use this:

如果你需要支持旧的 IE,你可以使用这个:

var addListener, removeListener;
if (document.addEventListener) {
    addListener = function (el, evt, f) { return el.addEventListener(evt, f, false); };
    removeListener = function (el, evt, f) { return el.removeEventListener(evt, f, false); };
} else {
    addListener = function (el, evt, f) { return el.attachEvent('on' + evt, f); };
    removeListener = function (el, evt, f) { return el.detachEvent('on' + evt, f); };
}

var myListener = function () {
    removeListener(document, 'mousemove', myListener);
    // do stuff
};

addListener(document, 'mousemove', myListener);

回答by Amit

(function(){
   var moved = false
   window.onmousemove = function(e){
      if(!moved){
          moved = true;
          // do what you want after mousemove, here
      }
   }
})()