You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript移动Div的代码问题:长按右键仅移动一次

Fixing the One-Time Movement Issue When Holding Right Arrow

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:34:12