JavaScript移动延迟和多次击键 [英] JavaScript move delay and multiple keystrokes
本文介绍了JavaScript移动延迟和多次击键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我的问题: http://testepi.kvalitne.cz/test/
我不希望按键和方块的移动之间有延迟。我还想知道如何对角移动(同时按两个键)。
I do not want the delay between a keypress and the movement of the square. I would also like to know how to move diagonally (pressing two keys at same time).
我的代码:
$(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事件所需的多个按键:
First, to avoid the keypress/repeat delay, you have to wrap your program in a loop, and make the state of the keyboard available inside the scope of that loop, secondly to monitor multiple keypresses you need to keep track of individual keydown and keyup events:
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移动延迟和多次击键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文