2014-08-27 53 views
2

我有一個方框.child。當按下鍵時,我想讓這個盒子跳轉,然後回到它的原始位置。我已經得到以下腳本:Jquery Animate - 使元素反彈一次

$(document).on('keydown', function(e){ 
    if (e.keyCode === 38) { 
     $('.child').animate({ 
      'bottom' : '50px' 
     }, 250).animate({ 
      'bottom' : '0px' 
     }, 250); 
    } 
}); 

現在它確實使按鈕向上按鍵時元素反彈。但是,如果我一直持續按下向上鍵,即使沒有按下鍵,它也會一直跳動。現在我知道了queue,所以我嘗試了以下內容:

$(document).on('keydown', function(e){ 
    if (e.keyCode === 38) { 
     $('.child').animate({ 
      'bottom' : '50px' 
     }, { 
      duration: 250, 
      queue: false 
     }).animate({ 
      'bottom' : '0px' 
     }, { 
      duration: 250, 
      queue: false 
     }); 
    } 
}); 

但隨着預期的要麼沒有工作。然後,我想添加queue : false第二動畫,但仍然沒有奏效。任何人都可以請告訴我如何讓元素跳躍一次而不是重複的跳躍?

小提琴這裏:http://jsfiddle.net/duwtbux0/

+0

對不起,但我不能重現你的問題(在FF 24上)。該按鈕每按一次按鈕就會跳轉一次(它會排隊進一步按下)。如果我按住按鈕,它會計算所有重複次數併爲每次重複跳躍一次。 – nfechner 2014-08-27 13:21:58

+1

這是他的問題,他不想排起一堆跳躍。 http://jsfiddle.net/duwtbux0/2/ – 2014-08-27 13:24:33

+0

@C鮑爾嗯,我讀了不同的問題:'即使沒有按下鍵,它仍然使框跳' – nfechner 2014-08-27 13:28:04

回答

3

只需添加某種標誌即可停止輸入被接受。

var acceptingInput = true; 
$(document).on('keydown', function(e){ 

    if(acceptingInput){ 
     if (e.keyCode === 38) { 
      acceptingInput = false; 
      $('.child').animate({ 
       'bottom' : '50px' 
      }, 250).animate({ 
       'bottom' : '0px' 
      }, 250, function() { 
       acceptingInput = true; 
      }); 
     } 
    } 
}); 

小提琴:http://jsfiddle.net/duwtbux0/2/

+0

但是...這不起作用...請檢查小提琴......歡呼聲:) – Hackerman 2014-08-27 13:26:36

+0

不,它的工作完美 – RajivRisi 2014-08-27 13:29:43

+0

在鉻,火狐和ie工作正常。乾杯。 – 2014-08-27 13:30:40

0

如果你想盒子反彈僅onces,您需要解除綁定的文件。該keydown聽衆。

$(document).on('keydown.bounce', function(e){ 
    if (e.keyCode === 38) { 
     $('.child').animate({ 
      'bottom' : '50px' 
     }, 250).animate({ 
      'bottom' : '0px' 
     }, 250); 
     $(document).unbind('.bounce'); 
    } 
}); 

隊列屬性不是爲了做你想做的。該隊列僅用於告訴jquery您是要立即執行動畫還是在最後一個動畫完成後執行動畫。

0
$(document).on('keydown', function(e){ 
    if($('.child').css('bottom') === '0px'){ 
    if (e.keyCode === 38) { 
     $('.child').animate({ 
      'bottom' : '50px' 
     }, 250).animate({ 
      'bottom' : '0px' 
     }, 250); 
    } 
    } 
}); 

這工作對我很好!

3

如果你想,這裏是另一種可能性:

$(document).on('keydown', function(e){ 
    if (e.keyCode === 38) { 
     $('.child').stop(1,0).animate({ 
      'bottom' : '50px' 
     }, 250).animate({ 
      'bottom' : '0px' 
     }, 250); 
    } 
}); 

添加.stop(1,0)將保持塊在空氣中,只要你反覆按向上鍵,也將停止排隊。

http://jsfiddle.net/duwtbux0/5/

這可能不是你在找什麼,但它是值得一提。

+0

實際上很酷,雖然它不適用於我的鉻,直到第二次反彈,這有點令人困惑。 – 2014-08-27 13:32:16