是否有可能在jQuery中按下键时元素会持续移动?
我尝试了几种方法,但它们总是在动画调用之间中断.我目前的代码:
$(document).keydown(function (e) {
if (e.which == 37) {
$('#you').stop().animate({
left: '-=16px'
}, 10);
}
});
$(document).keyup(function (e) {
$('#you').stop();
});
Run Code Online (Sandbox Code Playgroud)
.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;
} );
Run Code Online (Sandbox Code Playgroud)