我有以下的代码片段jQuery的连续鼠标按下
$(document).mousedown(function(event) {
doSomething();
}
我可以成功地捕捉到mousedown
事件。
我努力做到以下几点:
- 捕捉第一
mousedown
事件 - 我想检测用户是否仍持有按下鼠标,所以我可以做别的事情。
我有以下的代码片段jQuery的连续鼠标按下
$(document).mousedown(function(event) {
doSomething();
}
我可以成功地捕捉到mousedown
事件。
我努力做到以下几点:
mousedown
事件喜欢的东西
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;
});
您需要做一些类似于mouseDown
的事情,开始做点什么并继续做下去,直到mouseUp
事件被解雇。
我该如何继续做下去?使用setInterval()?谢谢。 – pion 2011-02-10 18:35:51
你会执行一些递归!
var mouseisdown = false;
$(document).mousedown(function(event) {
mouseisdown = true;
doSomething();
}).mouseup(function(event) {
mouseisdown = false;
});
function doSomething(){
//Code goes here
if (mouseisdown)
doSomething();
}
使用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.
}
}
希望帮助!
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 //
}
你也可以把一个clearInterval
上mouseleave
事件。
$(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);
}
}
});
你的意思是.... setInterval(“doSomething”,100); – mrbinky3000 2012-06-27 20:55:36
更好:setInterval(“doSomething()”,100); 您应该存储对时间间隔的引用,然后在再次调用setInterval之前将其清除(如果需要),否则可能会同时运行多个时间间隔。 – HaukurHaf 2013-04-02 13:10:19