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

我正在编写一个用箭头键移动的盒子。我想对其进行编程,以便当我按下键盘上的某个键时,间隔会检测按下的键并将数值放入名为 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;

}


慕田峪7331174
浏览 133回答 1
1回答

喵喵时光机

你有一个错误keyLifted。它应该拼接在i,而不是i - 1:function keyLifted(e, keyArray) {&nbsp; //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&nbsp; for (i = 0; i < keyArray.length; i++) {&nbsp; &nbsp; if (keyArray[i] == e.keyCode) {&nbsp; &nbsp; &nbsp; keyArray.splice(i, 1);&nbsp; &nbsp; &nbsp; console.log(keyArray);&nbsp; &nbsp; }&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript