gpt4 book ai didi

javascript - 按住某个键时连续移动

转载 作者:搜寻专家 更新时间:2023-11-01 04:27:43 26 4
gpt4 key购买 nike

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

关于javascript - 按住某个键时连续移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4193314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com