我正在编写一个用箭头键移动的盒子。我想对其进行编程,以便当我按下键盘上的某个键时,间隔会检测按下的键并将数值放入名为 KeyDown 的数组中。函数 keyPressed 检测 keyCode 是否已在 keyArray 中,以便不再调用它,并使框在屏幕上缩放,但以一致的速度缩放。如果 keyPressed 函数没有找到重复项,则会将其添加到要按时间间隔运行的数组中,并使用 moveMover 来移动盒子。然后,当按下的键被抬起时,该特定实例将从整个数组中拼接出来。
当我按向左键和箭头键时,程序会正常工作。但是,当我同时按下两个键时,程序无法拼接两个键,因此,其中一个键仍在运行。然后盒子不断向左或向右移动。我尝试用逻辑来寻找解决方案,但我不明白。
这是全html的盒子移动程序,带有css标签和样式标签。
function getTheStyle(id, styleProperty) {
var elem = document.getElementById(id);
var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue(styleProperty);
return theCSSprop;
}
function keyPressed(e, keyArray) {
//check if keyCode is already in the keyArray
for (i = 0; i < keyArray.length; i++) {
if (keyArray[i] == e.keyCode) {
return;
}
}
keyArray.push(e.keyCode);
}
function keyLifted(e, keyArray) {
//check for every instance of the keyCode and splice it out, theory one instance, go through key array and make sure there isnt a copy anywhere
for (i = 0; i < keyArray.length; i++) {
if (keyArray[i] == e.keyCode) {
keyArray.splice(i - 1, 1);
console.log(keyArray);
}
}
}
function moveMover(mover, keyArray) {
//loop through key array, if number 39, if finds left key getting pressed, then add 2
for (var i = 0; i < keyArray.length; i++) {
if (keyArray[i] == 39) {
//left
mover.style.left = parseInt(getTheStyle(mover.id, "left")) + 2 + "px";
console.log(keyArray);
} else if (keyArray[i] == 37) {
//right
mover.style.left = parseInt(getTheStyle(mover.id, "left")) - 2 + "px";
console.log(keyArray);
}
}
}
//-----------MAIN PROGRAM ----------------------
var MoverTimer; //timer for user controled element
var mover; //inner moving element
var keysDown = []; //all the currently depressed keys
window.onload = function() {
mover = document.getElementById("mover");
MoverTimer = setInterval(function() {
moveMover(mover, keysDown);
}, 5);
}
body {
background-color: skyblue;
}
喵喵时光机
相关分类