2010-11-16 78 views
5

在按住按鍵的情況下jQuery中有可能持續移動某個元素嗎?按住按鍵時的連續動作

我已經嘗試了幾種方法,但他們總是在動畫調用之間休息一下。代碼我目前有:

$(document).keydown(function (e) { 
    if (e.which == 37) { 
     $('#you').stop().animate({ 
      left: '-=16px' 
     }, 10); 
    } 
}); 
$(document).keyup(function (e) { 
    $('#you').stop(); 
}); 
+0

請顯示您的當前代碼。我想動畫調用有問題,而不是事件。 – Anpher 2010-11-16 11:10:06

+0

已編輯,但我認爲這不會有幫助。 – 2010-11-16 11:21:13

回答

3

.animate()並不總是最好的方法。

// cache jQuery objects for performance 
var you = $("#you") 
, doc = $(document) 

// variable to hold motion state 
, activeMotion 

// goDown motion, adjust numbers to taste 
, goDown = function(){ 
    you.css("left" , you.css("left") - 16); 
    if (activeMotion === goDown) { 
     setTimeout(goDown , 10); 
    } 
} 

doc.keydown(function(e) { 
    if (e.which === 37 && activeMotion !== goDown) { 
     activeMotion = goDown; 
     goDown(); 
    } 
    // all directions can go here in seperate if/else statements 
    // be sure to include "activeMotion !== goDown" else every time 
    // keydown event fires, it will start a new goDown loop. 
}); 

doc.keyup(function() { 
    // simply ends any motion that checked activeMotion 
    activeMotion = null; 
}); 
+0

這不會起作用:''''''''''''''''''''''''''''''''''至少現在''''''''''''''''''''''''''這個不會起作用:''''.css(「left」,「 - = 16px」)'','.css ..'.animate()'雖然。 – 2010-11-16 11:46:56

+0

@nick固定。動畫開始它自己的超時循環,總之更多的函數被調用並創建冗餘進程。動畫在平滑的動畫中從點a到b很好,對於有條件的增量步驟,最好像這樣實現它。 – BGerrissen 2010-11-16 11:50:32

+1

更好的方法是使用'offset'函數回調選項:'you.offset(function(idx,oldOffset){return {top:oldOffset.top,left:oldOffset.left - 16};}); ' – lonesomeday 2010-11-16 12:17:11

0

而不是動畫元素,而只是移動它的一些像素。 16可能會太多,因爲它會過快。

0

我想你會看到動畫調用之間的中斷,因爲你的時機。

如果你看看你的操作系統鍵盤重複時間間隔,它應該在35毫秒左右 - test it here

最重要的是你在動畫每10ms,這還不包括需要運行所有的動畫功能的時間,等等。所以,爲什麼不簡化的動畫,而無需擔心時間間隔(try this demo):

var block = $('.block'), 
    leftPos; 
$(document).keydown(function (e) { 
    leftPos = block.position().left; 
    leftPos += (e.which == 37) ? -5 : 0; 
    leftPos += (e.which == 39) ? 5 : 0; 
    block.css('left', leftPos); 
});