How to detect when mousemove has stopped

前端 未结 3 889
悲&欢浪女
悲&欢浪女 2020-12-16 11:57

How is it possible to detect with an eventListener when mousemove has finished?

document.AddEventListener(\'mousemove\', startInteractionTimer,          


        
3条回答
  •  自闭症患者
    2020-12-16 12:25

    Here is another custom-event solution, but without jQuery. It creates an event called mousestop which will be triggered on the element that the mouse pointer is on. It will bubble up like other mouse events.

    So once you have that piece of code included, you can add event listeners to any element with 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.
    });

    Title

    content content
    stop your mouse over this link for 1 second
    content content content

提交回复
热议问题