2012-12-30 45 views
11

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

+1

[确定鼠标是否仍然在javascript/jQuery中?](http://stackoverflow.com/questions/2487939/determine-if-mouse-is-still-in-javascript-jquery) –

回答

25

你可以听mousemove事件,一旦发生任何启动超时而取消任何现有超时。

var timeout = null; 

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

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

DEMO

这可以在不jQuery的很容易实现,以及(仅结合这里的事件处理程序的jQuery专用)。

+0

谢谢!这正是我正在寻找的。 :-D – ModernDesigner

+0

可能想要在定时器触发后将'timeout'设置回'null',以避免执行无效的'clearTimeout()'。 – jfriend00

+0

@ jfriend00:没关系,真的。 http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-cleartimeout即使是'null'检查。 – Ryan

9

无需插件,甚至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); 
})(); 
相关问题