jQuery - detect if the mouse is still?

梦想与她 提交于 2020-01-12 03:17:54

问题


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!


回答1:


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

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).




回答2:


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

(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);
})();


来源:https://stackoverflow.com/questions/14094272/jquery-detect-if-the-mouse-is-still

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!