jQuery连续mousedown

pio*_*ion 16 javascript jquery

我有以下代码片段

$(document).mousedown(function(event) {
    doSomething();
}
Run Code Online (Sandbox Code Playgroud)

我可以mousedown成功捕获事件.

我正在尝试执行以下操作:

  1. 捕获第一个mousedown事件
  2. 我想检测用户是否仍然按住鼠标,以便我可以做其他事情.

Ric*_*iwi 26

就像是

var mouseStillDown = false;

$(document).mousedown(function(event) {
    mouseStillDown = true;
    doSomething();
});

function doSomething() {
    if (!mouseStillDown) { return; } // we could have come back from
                                     // SetInterval and the mouse is no longer down
    // do something

    if (mouseStillDown) { setInterval("doSomething", 100); }
}

$(document).mouseup(function(event) {
    mouseStillDown = false;
});
Run Code Online (Sandbox Code Playgroud)

  • 如果我没有弄错的话,上面的代码将同时生成许多同时运行的间隔,不断创建更多,这真的很糟糕.单个间隔的正确解决方案随后将被清除:http://stackoverflow.com/a/8010163/2855804 (5认同)

小智 20

var int00; // declared here to make it visible to clearInterval.

$('#trigger').mousedown(function(){
    int00 = setInterval(function() { repeatingfunction(); }, 50);
}).mouseup(function() {
    clearInterval(int00);
});

function repeatingfunction() {
    // This will repeat //
}
Run Code Online (Sandbox Code Playgroud)

你也可以clearInterval参加mouseleave活动.

  • 优雅的解决方案,但一个小错字.. setInterval :) (2认同)

Nic*_*ers 5

你实现了一些递归!

var mouseisdown = false;

$(document).mousedown(function(event) {
    mouseisdown = true;
    doSomething();
}).mouseup(function(event) {
    mouseisdown = false;
});

function doSomething(){
    //Code goes here
    if (mouseisdown)
        doSomething();
}
Run Code Online (Sandbox Code Playgroud)