2010-10-20 207 views
22

我需要執行,而按下一個按鈕的功能和停止按鈕時,放手jQuery的:鼠標按下效果(而按左鍵按住)

$('#button').--while being held down--(function() { 
    //execute continuously 
}); 
+0

看看我的問題,這是基於這個問題。有一個改進,這一個:http://stackoverflow.com/questions/36316638/jquery-mousdown-with-setinterval-endless – Steckdoserich 2016-03-30 19:14:40

回答

46

執行的功能,我相信這樣的事情會工作:

var timeout, clicker = $('#clicker'); 

clicker.mousedown(function(){ 
    timeout = setInterval(function(){ 
     // Do something continuously 
    }, 500); 

    return false; 
}); 

$(document).mouseup(function(){ 
    clearInterval(timeout); 
    return false; 
}); 

看到這個演示:http://jsfiddle.net/8FmRd/

+12

一個問題 - 如果你放開命中區域,效果永遠循環。你應該考慮在整個文檔上使用'mouseup'函數,而不是'clicker'。 – Jeriko 2010-10-20 11:12:09

+2

@Jeriko你說得對。我現在編輯我的答案 – 2010-10-20 11:14:35

+0

或者,他可能想要使用mousemove事件而不是setInterval解決方案。 – kapa 2010-10-20 11:19:48

17

一個小的修改原來的答案:

$('#Clicker').mousedown(function() { 
    //do something here 
    timeout = setInterval(function() { 
     //do same thing here again 
    }, 500); 

    return false; 
}); 
$('#Clicker').mouseup(function() { 
    clearInterval(timeout); 
    return false; 
}); 
$('#Clicker').mouseout(function() { 
    clearInterval(timeout); 
    return false; 
}); 

隨着Clicker上的鼠標移出事件,它會在您將鼠標移出點擊區域時停止。

我建議兩次做同樣的事情的原因是爲了獲得更平滑的效果。如果你在超時被設置之前不做一次,那麼在這種情況下,延遲500毫秒纔會發生。

1
$.fn.click2=function(cb,interval){ 
    var timeout; 
    if(!interval) interval=100; 
    $(this).mousedown(function() { 
     var target=this; 
     timeout = setInterval(function(){ 
      cb.apply(target); 
     }, interval); 

    return false; 
    }).mouseup(function() { 
     clearInterval(timeout); 
     return false; 
    }).mouseout(function() { 
     clearInterval(timeout); 
     return false; 
    }); 
} 
1

下面是提供的解決方案的純JavaScript實現,它擴展了對觸摸屏的支持。您提供id,action執行(function(){})和interval(ms)重複action。請注意,此實現也將立即執行action,而不是等待interval失效。

// Configures an element to execute a function periodically whilst it holds the user's attention via a mouse press and hold. 
function assertPeriodicPress(id, action, interval) { 
    // Listen for the MouseDown event. 
    document.getElementById(id).addEventListener('mousedown', function(ev) { action(); timeout = setInterval(action, interval); return false; }, false); 
    // Listen for mouse up events. 
    document.getElementById(id).addEventListener('mouseup', function(ev) { clearInterval(timeout); return false; }, false); 
    // Listen out for touch end events. 
    document.getElementById(id).addEventListener('touchend', function(ev) { clearInterval(timeout); return false; }, false); 
}