javascript jQuery - 检测鼠标是否还在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14094272/
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 20:41:42  来源:igfitidea点击:

jQuery - detect if the mouse is still?

javascriptjquerypluginsmouse

提问by ModernDesigner

I was wondering if there was a way to detect if the mouse is idle for like 3 seconds in jQuery. Is there a plugin that I am unaware of? Because I don't believe there to be a native jQuery method. Any help would be much appreciated!

我想知道是否有一种方法可以检测鼠标是否在 jQuery 中闲置了 3 秒钟。有没有我不知道的插件?因为我不相信有原生的 jQuery 方法。任何帮助将非常感激!

回答by Felix Kling

You can listen to the mousemoveevent, start a timeout whenever it occurs and cancel any existing timeout.

您可以监听mousemove事件,在它发生时启动超时并取消任何现有的超时。

var timeout = null;

$(document).on('mousemove', function() {
    clearTimeout(timeout);

    timeout = setTimeout(function() {
        console.log('Mouse idle for 3 sec');
    }, 3000);
});

DEMO

演示

This can be very easily done without jQuery as well (only binding the event handler here is jQuery-specific).

这也可以很容易地在没有 jQuery 的情况下完成(这里只绑定事件处理程序是特定于 jQuery 的)。

回答by Niet the Dark Absol

No need for a plugin, or even for jQuery at all:

不需要插件,甚至根本不需要 jQuery:

(function() {
    var idlefunction = function() {
          // what to do when mouse is idle
        }, idletimer,
        idlestart = function() {idletimer = setTimeout(idlefunction,3000);},
        idlebreak = function() {clearTimeout(idletimer); idlestart();};
    if( window.addEventListener)
        document.documentElement.addEventListener("mousemove",idlebreak,true);
    else
        document.documentElement.attachEvent("onmousemove",idlebreak,true);
})();