如何检测mousemove何时停止

sup*_*ize 19 html javascript jquery

如何在mousemove完成后使用eventListener进行检测?

document.AddEventListener('mousemove', startInteractionTimer, false);

function startInteractionTimer(){
  clearInterval(touchInterval);
  touchInterval = setInterval(noAction, 6000);
}
Run Code Online (Sandbox Code Playgroud)

我想startInteractionTimer在mousemove结束后立即启动该功能,我想抓住它.在上面的代码示例中,如果移动鼠标,它将启动.

谢谢

编辑:好吧,我回答了我自己的问题和上面的脚本 - ^很好.

Nat*_*nes 13

您可以随时为其创建自定义事件:

(function ($) {
    var timeout;
    $(document).on('mousemove', function (event) {
        if (timeout !== undefined) {
            window.clearTimeout(timeout);
        }
        timeout = window.setTimeout(function () {
            // trigger the new event on event.target, so that it can bubble appropriately
            $(event.target).trigger('mousemoveend');
        }, 100);
    });
}(jQuery));
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

$('#my-el').on('mousemoveend', function () {
    ...
});
Run Code Online (Sandbox Code Playgroud)

编辑:

此外,为了与其他jQuery事件保持一致:

(function ($) {
    $.fn.mousemoveend = function (cb) {
        return this.on('mousemoveend', cb);
    });
}(jQuery));
Run Code Online (Sandbox Code Playgroud)

现在你可以:

$('#my-el').mousemoveend(fn);
Run Code Online (Sandbox Code Playgroud)


Jef*_*ver 9

您可以尝试仅设置/清除超时以检测移动鼠标的结束...

var x;
document.addEventListener('mousemove', function() { 
    if (x) clearTimeout(x); 
    x = setTimeout(startInteractionTimer, 200); 
}, false);
Run Code Online (Sandbox Code Playgroud)

你想等多久取决于你.我不知道你想说多久是"鼠尾草的结束"

示例:http://jsfiddle.net/jeffshaver/ZjHD6/


tri*_*cot 5

这是另一个自定义事件解决方案,但没有jQuery。它创建一个称为的事件mousestop,该事件将在鼠标指针所在的元素上触发。它将像其他鼠标事件一样冒泡。

因此,一旦包含了这段代码,就可以使用以下命令将事件侦听器添加到任何元素addEventListener('mousestop', fn)

(function (mouseStopDelay) {
    var timeout;
    document.addEventListener('mousemove', function (e) {
        clearTimeout(timeout);
        timeout = setTimeout(function () {
            var event = new CustomEvent("mousestop", {
                detail: {
                    clientX: e.clientX,
                    clientY: e.clientY
                },
                bubbles: true,
                cancelable: true
            });
            e.target.dispatchEvent(event);
        }, mouseStopDelay);
    });
}(1000));

// Example use
document.getElementById('link').addEventListener('mousestop', function(e) {
    console.log('You stopped your mouse while on the link');
    console.log('Mouse coordinates are: ', e.detail.clientX, e.detail.clientY);
    // The event will bubble up to parent elements.
});
Run Code Online (Sandbox Code Playgroud)
<h1>Title</h1>
<div>
    content content<br>
    <a id="link" href="#">stop your mouse over this link for 1 second</a><br>
    content content content
</div>
Run Code Online (Sandbox Code Playgroud)