开发者

Continuous movement when a key is held down

Is it possible in jQuery to have an element continuously move when the key is held down?

I've tried a few ways but they always have a break in between animation calls. The code I currently have:

$(document).keydown(function (e) {
    if (e.which == 37) {
        $('#you').stop().animate({
            left: '-=16px'
        }, 10);
    }
});
开发者_运维百科$(document).keyup(function (e) {
    $('#you').stop();
});


.animate() isn't always the best way.

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


Instead of animating the element, rather just move it by some amount of pixels. 16 will probably be too much because it will go too fast.


I think you are seeing the break between animation calls because of your timing.

If you look at your operating systems keyboard repeat time interval, it should be around 35 milliseconds - test it here.

On top of that you are animating every 10ms, not counting the time it takes to run all the animation functions, etc. So why not simplify the animation and not worry about time intervals (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);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜