使用JavaScript移动Div的代码问题:长按右键仅移动一次
Got it, let's figure out why your red player div only moves once when you hold the right arrow key—there are two key issues here, plus a small CSS mismatch to clean up.
1. The Root Problem: Resetting Position on Every Key Press
Look at your BeginningPos variable: you declare it inside the KeyPressed function. That means every time you press (or hold) a key, this variable gets reset to 0 before you add 20 to it. So no matter how many times the event fires, you're always setting the player's left position to 0 + 20 = 20px—hence the one-time move.
To fix this, move BeginningPos outside the function so it retains its value between key presses.
2. CSS Selector Mismatch
Your HTML uses <div id="GameBackground"> but your CSS targets #Background—this means your background styling won't apply at all. Update the CSS selector to match the HTML id to get your game background working as intended.
Fixed Full Code
HTML
<div id="GameBackground"> <div id="Player"></div> </div>
CSS
#GameBackground { height:400px; width:600px; outline: 5px solid black; position:relative; } #Player { position:absolute; height:20px; width:40px; outline: 5px solid black; background-color:red; left: 0; font-size:10px; color:#fff; padding:20px; }
JavaScript
// Keep track of position outside the function so it persists between key presses let BeginningPos = 0; document.onkeydown = KeyPressed; function KeyPressed(k) { const RightBtn = 39; const Player = document.getElementById("Player"); if (k.keyCode == RightBtn) { BeginningPos += 20; // Add 20 to the current saved position Player.style.left = BeginningPos + "px"; } }
Bonus: Smoother Long Press Behavior
Some browsers have a small delay before repeating keydown events when holding a key. If you want even smoother movement, you could use setInterval on keydown and clear it on keyup, but the fix above already solves your core issue of one-time movement.
内容的提问来源于stack exchange,提问作者Clint Anumudu

