我正在編寫一個用箭頭鍵移動的盒子。我想對其進行編程,以便當我按下鍵盤上的某個鍵時,間隔會檢測按下的鍵并將數(shù)值放入名為 KeyDown 的數(shù)組中。函數(shù) keyPressed 檢測 keyCode 是否已在 keyArray 中,以便不再調(diào)用它,并使框在屏幕上縮放,但以一致的速度縮放。如果 keyPressed 函數(shù)沒有找到重復(fù)項,則會將其添加到要按時間間隔運行的數(shù)組中,并使用 moveMover 來移動盒子。然后,當按下的鍵被抬起時,該特定實例將從整個數(shù)組中拼接出來。當我按向左鍵和箭頭鍵時,程序會正常工作。但是,當我同時按下兩個鍵時,程序無法拼接兩個鍵,因此,其中一個鍵仍在運行。然后盒子不斷向左或向右移動。我嘗試用邏輯來尋找解決方案,但我不明白。這是全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 elementvar mover; //inner moving elementvar keysDown = []; //all the currently depressed keyswindow.onload = function() { mover = document.getElementById("mover"); MoverTimer = setInterval(function() { moveMover(mover, keysDown); }, 5);}body { background-color: skyblue;}
如何修復(fù)此 Javascript 程序中的移動錯誤,使其在同時按下兩個鍵時不會中斷?
慕田峪7331174
2023-08-24 15:50:03