在jQuery中,当按住键时是否可以使元素连续移动?

我尝试了几种方法,但它们总是在动画调用之间有所中断。我目前拥有的代码:

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

最佳答案

.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;
} );

08-08 07:03