繁体   English   中英

如何修复此 Javascript 程序中的移动错误,使其在我同时按下两个键时不会中断?

[英]How do I fix my movement error in this Javascript program so it doesn't break when I press two keys at the same time?

我正在编写一个用箭头键移动的框。 我想对它进行编程,以便当我按下键盘上的一个键时,间隔检测按下的键并将数值放入一个名为 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; } #mover { position: absolute; top: 100px; left: 130px; z-index: 2; background-color: green; width: 50px; height: 50px; border: 2px solid black; }
 <html> <head> <title>Two Movers</title> </head> <body onkeydown="keyPressed(event,keysDown)" onkeyup="keyLifted(event,keysDown)"> <div id="mover"></div> </body>

您在keyLifted有一个错误。 它应该拼接在i ,而不是i - 1

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);
      console.log(keyArray);
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM