2013-03-26 73 views
3

我在按鍵動畫div,但如果我按下箭頭2倍,然後我的動畫中斷, 有沒有辦法讓我只能在1秒後按鍵?1秒後允許按鍵

$(document).keyup(function(e){ 
    if (e.keyCode == 38) { 
     $('.selected').animate({'top':'300px'},500); 
     $('.section.selected').removeClass('selected') 
           .next('.section').animate({'top':'0'},500) 
           .addClass('selected'); 
     return false; 
    } 
    e.preventDefault(); 
}); 

回答

1

爲了字面上實現您的要求儘可能:

var allowKeyPress = true; 
$(document).keyup(function(e){ 
if (e.keyCode == 38) { 
    if (!allowKeyPress) 
     return false; 
    allowKeyPress = false; 
    setTimeout(function() { allowKeyPress = true; }, 1000); 

    $('.selected').animate({'top':'300px'},500); 
    $('.section.selected').removeClass('selected').next('.section').animate({'top':'0'},500).addClass('selected'); 
    return false;  
    }  
    e.preventDefault(); 
}); 

也就是說,使用標誌,allowKeyPress - 上KEYUP檢驗標誌是否爲false,如果是立即停止。否則,請繼續,將標誌設置爲false並使用setTimeout()安排一秒鐘後運行的功能將標誌設置回true,當然還需要運行動畫。

+0

Awesommmme ..這工作!謝謝大家:) – itsMe 2013-03-26 12:17:40

0

試試這個:

$(document).keyup(function(e){ 
    if (e.keyCode == 38 && !$('.selected').is(':animated')) { 
      $('.selected').animate({'top':'300px'},500); 
      $('.section .selected').removeClass('selected') 
           .next('.section') 
           .animate({'top':'0px','position':'relative'},500) 
           .addClass('selected'); 
      return false; 
     } 
     e.preventDefault(); 
}); 
+0

OP想要在同一個1秒的時間內阻止兩個按鍵,不會延遲1秒鐘的所有按鍵。 – nnnnnn 2013-03-26 12:03:22

1

檢查元素被觸發進一步動畫之前動畫:

$(document).keyup(function(e){ 
    if (e.keyCode == 38) { 
    if(!$('.selected').is(':animated')){ 

     $('.selected').animate({'top':'300px'},500);  
     $('.section.selected').removeClass('selected').next('.section').animate({'top':'0'},500).addClass('selected'); 
     return false; 
    } 
    }  
    e.preventDefault(); 
}); 
+1

擺弄時間是凌亂的生意。這好多了。 +1 – SomeShinyObject 2013-03-26 12:03:49

0

你可以找出是否有任何元素的動畫並取消新的動畫。 所以把下面的代碼作爲第一行到你的按鍵功能。

if($(".selected").is(":animated")) return;