简体   繁体   English

按住键时连续移动

[英]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? 是否有可能在jQuery中按下键时元素会持续移动?

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

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. 16可能会太多,因为它会太快。

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 . 如果你看看你的操作系统键盘重复时间间隔,它应该是大约35毫秒 - 在这里测试它

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 ): 最重要的是,你每10ms动画一次,不计算运行所有动画功能所花费的时间等等。那么为什么不简化动画而不用担心时间间隔( 试试这个演示 ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM