网页游戏角色无法左右移动问题求助(附代码)
解决角色无法左右移动的问题
嘿,我帮你排查了代码里的问题,核心是一个拼写错误,还有几个潜在的小问题,咱们一步步来修复:
1. 最关键的拼写错误
你在getComputedStyle后面调用的getPropertyvalue是错的,正确的方法名是getPropertyValue(最后一个字母V是大写)!这个错误会导致你无法正确获取角色的left属性值,自然没法计算移动后的位置。
2. 潜在的样式缺失问题
如果你的#character元素没有设置定位属性和初始left值,window.getComputedStyle获取到的left可能是auto,parseInt之后会变成NaN,导致样式设置失效。所以需要给角色加基础CSS样式。
修正后的完整代码
HTML
<div id="game"> <div id="character"></div> </div>
CSS
#game { position: relative; width: 400px; height: 200px; border: 1px solid #000; } #character { position: absolute; /* 必须设置定位才能用left属性 */ left: 0; /* 初始left值 */ width: 20px; height: 20px; background-color: red; }
JavaScript
var character = document.getElementById("character"); var interval; var both = 0; function moveLeft() { // 修正拼写错误:getPropertyValue var left = parseInt(window.getComputedStyle(character).getPropertyValue("left")); character.style.left = left - 2 + "px"; } function moveRight() { // 同样修正拼写错误 var left = parseInt(window.getComputedStyle(character).getPropertyValue("left")); character.style.left = left + 2 + "px"; } document.addEventListener("keydown", event => { if (both == 0) { both++; if (event.key === "ArrowLeft") { interval = setInterval(moveLeft, 1); } if (event.key === "ArrowRight") { interval = setInterval(moveRight, 1); } } }); document.addEventListener("keyup", event => { clearInterval(interval); both = 0; });
额外优化建议
- 可以给移动速度加个变量,比如
const speed = 2;,这样修改速度更方便。 - 可以限制角色的移动范围,避免角色跑到游戏容器外面:
function moveLeft() { var left = parseInt(window.getComputedStyle(character).getPropertyValue("left")); if (left > 0) { // 限制左边界 character.style.left = left - 2 + "px"; } } function moveRight() { var left = parseInt(window.getComputedStyle(character).getPropertyValue("left")); // 游戏容器宽度减去角色宽度,限制右边界 if (left < (parseInt(window.getComputedStyle(document.getElementById("game")).getPropertyValue("width")) - 20)) { character.style.left = left + 2 + "px"; } }
内容的提问来源于stack exchange,提问作者Chikenlegpiece
相关产品推荐
相关产品推荐

