2011-02-10 63 views
15

我有以下的代码片段jQuery的连续鼠标按下

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

我可以成功地捕捉到mousedown事件。

我努力做到以下几点:

  1. 捕捉第一mousedown事件
  2. 我想检测用户是否仍持有按下鼠标,所以我可以做别的事情。

回答

24

喜欢的东西

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; 
}); 
+0

你的意思是.... setInterval(“doSomething”,100); – mrbinky3000 2012-06-27 20:55:36

+0

更好:setInterval(“doSomething()”,100); 您应该存储对时间间隔的引用,然后在再次调用setInterval之前将其清除(如果需要),否则可能会同时运行多个时间间隔。 – HaukurHaf 2013-04-02 13:10:19

1

您需要做一些类似于mouseDown的事情,开始做点什么并继续做下去,直到mouseUp事件被解雇。

+0

我该如何继续做下去?使用setInterval()?谢谢。 – pion 2011-02-10 18:35:51

5

你会执行一些递归!

var mouseisdown = false; 

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

function doSomething(){ 
    //Code goes here 
    if (mouseisdown) 
     doSomething(); 
} 
1

使用mousedown事件来设置标志,并使用mouseup来取消设置标志。然后你可以简单地检查标志,看看它是否设置。

〔实施例

var mouseDownFlag = false; 
$(document).mousedown(function(event) { 
    mouseDownFlag = true; 
    someFunc(); 
} 
$(document).mouseup(function(event) { 
    mouseUpFlag = true; 
} 
var someFunc = function(){ 
    if(mouseDownFLag){//only run this function when the mouse is clicked 
    // your code 
     setTimeout("somefunc()", 1000); //run this function once per second if your mouse is down. 
    } 
} 

希望帮助!

16
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 // 
} 

你也可以把一个clearIntervalmouseleave事件。

1
$(document).ready(function(){ 

    var mouseStillDown = false; 

    $('#some_element').mousedown(function() { 
    do_something(); 
    }).mouseup(function() { 
    clearInterval(mouseStillDown); 
    mouseStillDown = false; 
    }); 

    function do_something() { 

    // add some code here that repeats while mouse down 

    if (!mouseStillDown) { 
     mouseStillDown = setInterval(do_something, 100); 
    } 

    } 

});