23

終了したときに eventListener で検出するにはどうすればよいmousemoveですか?

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

function startInteractionTimer(){
  clearInterval(touchInterval);
  touchInterval = setInterval(noAction, 6000);
}

startInteractionTimermousemove が終了した直後に関数を開始したいので、それをキャッチしたいと思います。上記のコード例では、マウスを動かすと開始しています。

ありがとう

編集:さて、私は自分の質問に答えました。上記のスクリプトは --^ で十分です。

4

3 に答える 3

17

いつでもカスタム イベントを作成できます。

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

今、あなたはこれを行うことができます:

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

編集:

また、他の jQuery イベントとの一貫性のために:

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

次のことができるようになりました。

$('#my-el').mousemoveend(fn);
于 2013-02-25T13:18:24.253 に答える
11

マウスの移動の終了を検出するためだけに、タイムアウトの設定/クリアを試みることができます...

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

どのくらい待ちたいかはあなた次第です。「マウスムーブの終わり」とはどれくらい言いたいのかわかりません

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

于 2013-02-25T12:31:06.103 に答える
8

別のカスタム イベント ソリューションを次に示しますが、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.
});
<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>

于 2016-09-28T20:02:28.340 に答える