1

How can I know how long a user has been holding the mouse button down (anywhere on a webpage)? I want to execute a function when the user held the mouse button for at least 2-3 seconds (preferably cancelling the mouse down in the process). Is this possible?

4

4 に答える 4

15

どうぞ:

$(window).mousedown(function(e) {
    clearTimeout(this.downTimer);
    this.downTimer = setTimeout(function() {
        // do your thing 
    }, 2000);
}).mouseup(function(e) {
    clearTimeout(this.downTimer);
});

ライブデモ: http: //jsfiddle.net/simevidas/Pe9sq/2/

于 2011-05-22T22:07:01.817 に答える
1

手元では$("body").mousedown(function(){})、jQueryとを使用して実験し$("body").mouseup(function(){})ます。2〜3秒で関数を呼び出すタイマーを開始できると思います。イベントが発生した場合はmouseup、タイマーをキャンセルできます。おそらく簡単なスクリプトでテストできますclickが、ページ上のリンクまたはボタンがクリックされたために発生した可能性のあるケースを調べる必要がある場合があります。$("body").mousedownしかし、出発点として、とを試してみ$("body").mouseupます。機会があれば、コードサンプルを送信できるかどうかを確認します。

于 2011-05-22T22:01:04.400 に答える
0

これを試して:

function WhateverYoudLikeToExecWithinNext3Seconds(){
    // Code goes here.
}

element.addEventListener('mousedown', function(){
    setTimeout(function(){WhateverIdLikeToExecWithin3Seconds();}, 3000);
}, false);
于 2011-05-22T22:13:49.910 に答える
0

これをチェックしてください。 http://jsfiddle.net/b1Lzo60n/

Mousedownは、マウスが1秒後にまだダウンしているかどうかをチェックするタイマーを開始します。

<button id="button">Press me</button>
<div id="log"></div>

コード:

var mousedown = false;
var mousedown_timer = '';
$('#button').mousedown(function(e) {
    mousedown = true;
    $('#log').text('mousedown...');
    mousedown_timer = setTimeout(function() {
        if(mousedown) {
            $('#log').text('1 second');
        }
    }, 1000);
}).mouseup(function(e) {
    mousedown = false;
    clearTimeout(mousedown_timer);
    $('#log').text('aborted');
});
于 2015-02-26T05:23:02.677 に答える