如果少于两秒的呼叫function2,我怎么能保持按住两秒钟的呼叫function1?

我有这个按钮,在一段时间内保持按钮不能正常工作(但它的工作方式就像点击一样)。

如果按钮hold大于/等于2秒然后callfunction1 ,如果按下按钮少于2秒然后callfuntion2 callfunction1 ,我试图这样做。

 var clickDisabled = false; function clickLocker() { /* @Button: 2 seconds */ clickDisabled = true; setTimeout(function(){clickDisabled = false;}, 2000); } function callfunction1() { // you have hold he button for greater then or equal 2 second } function callfunction2() { // you have hold the button less then 2 second } $('.button').live("click",function() { if (clickDisabled) { alert("locked for 2 second"); return; } clickLocker(); }); 

这是斜线的一个很好的建议。 这就是你如何做到这一点

 var clickstart; var clickstop; $("a").on('mousedown', function(e) { clickstart = e.timeStamp; }).on('mouseup', function(e) { clickstop = e.timeStamp- clickstart if(clickstop >= 2000) two() else one(); }); 

演示


更新:

可能有必要像@MarkRhodes在评论中所写的那样跟踪鼠标移动。 为此,请检查此更新

收听事件,mousedown和mouseup,测量两者之间的时间:

  var timeDown; var timeUp; $('.button').live("mousedown",function(){ timeDown = event.timeStamp; }); $('.button').live("mouseup",function(){ timeUp = event.timeStamp; time = timeUp-timeDown; if (time>2000){ function1(); }else{ function2(); } }); 

请注意event.timeStamp在firefox中不能正常工作。 对于firefox你可以做(​​新日期).getTime();

我认为这个解决方案应该有效。 我没有测试过,但它应该给你正确的想法。

 var startTime; function callfunction1() { // you have hold he button for greater then or equal 2 second } function callfunction2() { // you have hold the button less then 2 second } function buttonDownEvent() { var Time = new Date(); startTime = Time.getTime(); } function buttonUpEvent() { if(new Date().getTime() - startTime < 2000) callfunction2() else callfunction1() } $('.button').live("mousedown",function() { buttonDownEvent(); }); $('.button').live("mouseup",function() { buttonUpEvent(); }); 

您可以使用事件对mouseup和mousedown事件执行此操作,并计算它们之间的差异。 此外,您需要记住哪个元素导致了点击 – 如果用户在另一个元素上释放鼠标,那么它应该只执行“非2秒保持”function。 这里有一个显示这个工作的JSFiddle: http : //jsfiddle.net/35rw3/6/ 。