How to detect when mousemove has stopped

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

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

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


        
3条回答
  •  旧时难觅i
    2020-12-16 12:49

    You could always make a custom event for it:

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

    Now you can just do this:

    $('#my-el').on('mousemoveend', function () {
        ...
    });
    

    Edit:

    Also, for consistency with other jQuery events:

    (function ($) {
        $.fn.mousemoveend = function (cb) {
            return this.on('mousemoveend', cb);
        });
    }(jQuery));
    

    Now you can:

    $('#my-el').mousemoveend(fn);
    

提交回复
热议问题