gpt4 book ai didi

JavaScript 移动延迟和多次击键

转载 作者:行者123 更新时间:2023-11-30 08:58:44 25 4
gpt4 key购买 nike

这是我的问题:http://testepi.kvalitne.cz/test/

我不希望按键和方 block 移动之间有延迟。我也想知道如何对 Angular 移动(同时按下两个键)。

我的代码:

$(function(){

document.addEventListener("keydown", move, false);

var x = 0;
var y = 0;

function move(event){
if(event.keyCode==37){
x -= 10;
$("#square").css("left", x);
}

if(event.keyCode==39){
x += 10;
$("#square").css("left", x);
}

if(event.keyCode==38){
y -= 10;
$("#square").css("top", y);
}

if(event.keyCode==40){
y += 10;
$("#square").css("top", y);
}

}

});

最佳答案

首先,为了避免按键/重复延迟,您必须将程序包装在一个循环中,并使键盘状态在该循环范围内可用,其次要监视多个按键,您需要跟踪各个按键keydown 和 keyup 事件:

var x = 0;
var y = 0;

// store the current pressed keys in an array
var keys = [];

// if the pressed key is 38 (w) then keys[38] will be true
// keys [38] will remain true untill the key is released (below)
// the same is true for any other key, we can now detect multiple
// keypresses
$(document).keydown(function (e) {
keys[e.keyCode] = true;
});

$(document).keyup(function (e) {
delete keys[e.keyCode];
});
// we use this function to call our mainLoop function every 200ms
// so we are not relying on the key events to move our square
setInterval( mainLoop , 200 );

function mainLoop() {
// here we query the array for each keyCode and execute the required actions
if(keys[37]){
x -= 10;
$("#square").css("left", x);
}

if(keys[39]){
x += 10;
$("#square").css("left", x);
}

if(keys[38]){
y -= 10;
$("#square").css("top", y);
}

if(keys[40]){
y += 10;
$("#square").css("top", y);
}
}

关于JavaScript 移动延迟和多次击键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11197220/

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