2013-03-26 75 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;