window addEventListener 按键不工作

window addEventListener keydown not working

我正在编写一个游戏,当您按下箭头键时,立方体会在屏幕上移动。但它不起作用。有人可以帮我吗?

var playerElement = document.getElementById('playerEl');
var playerY = 0;
var playerX = 0;
window.addEventListener('keydown', function(e) {
  switch (e.keyCode) {
    case 37:
      playerX -= 100;
      playerElement.style.transform = "translate(" + playerX + '%,' + playerY + "%);";
      break;
    case 38:
      playerY -= 100;
      playerElement.style.transform = "translate(" + playerX + '%,' + playerY + "%);";
      break;
    case 39:
      playerX += 100;
      playerElement.style.transform = "translate(" + playerX + '%,' + playerY + "%);";
      break;
    case 40:
      playerY += 100;
      playerElement.style.transform = "translate(" + playerX + '%,' + playerY + "%);";
      break;
  }
}, true);
#playerEl {
  width: 50px;
  height: 50px;
  background: grey;
  display: inline-block;
  transform: translate(1%, 1%);
}
<body style="height:100vh;width:100vw;">
  <div id="playerEl"></div>
</body>

当使用 javascript 设置 transform style 属性 时,您不必在字符串中添加 ;

应该这样做:

playerElement.style.transform = "translate(" + playerX + '%,' + playerY + "%)";

这是您的代码,在 transform 字符串中没有 ;

var playerElement = document.getElementById('playerEl');
var playerY = 0;
var playerX = 0;
window.addEventListener('keydown', function(e) {
  switch (e.keyCode) {
    case 37:
      playerX -= 100;
      playerElement.style.transform = "translate(" + playerX + '%,' + playerY + "%)"; // Removed semi-colon from string
      break;
    case 38:
      playerY -= 100;
      playerElement.style.transform = "translate(" + playerX + '%,' + playerY + "%)"; // Removed semi-colon from string
      break;
    case 39:
      playerX += 100;
      playerElement.style.transform = "translate(" + playerX + '%,' + playerY + "%)"; // Removed semi-colon from string
      break;
    case 40:
      playerY += 100;
      playerElement.style.transform = "translate(" + playerX + '%,' + playerY + "%)"; // Removed semi-colon from string
      break;
  }
}, true);
#playerEl {
  width: 50px;
  height: 50px;
  background: grey;
  display: inline-block;
  transform: translate(1%, 1%);
}
<body style="height:100vh;width:100vw;">
  <div id="playerEl"></div>
</body>