按键上的Javascript:player.style.left += 10,无法弄清楚为什么这不起作用



我正在尝试移动我的角色(在变量'player'下保存,并且绝对位置。)'D'Keys。但是我无法移动。任何帮助都会很棒。

let player;
let bod;
player_one_horizontal_position;
window.onload = function(){
   bod = document.getElementsByTagName('body');
   player = document.getElementById('player');
   player_one_horizontal_position = 10;  
  bod.addEventListener('keydown',function(e){
  if(e.code === 'KeyA'){ 
        player_one_horizontal_position += 10; 
        check_position(e.code);  
    };
 }); //end of eventListener
   }//end of window.onload function
function check_position(code){
    console.log(code === 'KeyA'); /*does evaluate to true so the problem must be the next line */
    player.style.left = player_one_horizontal_position;
}

我在本周早些时候与jQuery做了类似的事情,所以我不确定为什么这不使用Vanilla JS

html:

<!DOCTYPE html>
<html>
<head>
    <!-- Main stylesheets -->
    <link rel="stylesheet" href="style.css"/> 
    <!-- Player stylesheets -->
    <link rel="stylesheet" href="player_one.css"/> 
    <link rel="stylesheet" href="player_two.css"/> 
    <script src="script.js"></script>
</head>
<body>
    <div id="wrapper">
        <div id="player" class="stance_one"></div>
        <div id="player2" class="first_stance"></div>
    </div>
</body> 
</html>

css for Player One:

#player{
    background-image: url('images/sprite.png');
    position: absolute;
    z-index: 1;
    height: 142px;
    left: 10;   
}
.stance_one{
    width: 8%;
    background-position: 0% 0%;
} 

如注释中所述,左侧必须有一个单元。这是一个工作示例:

var player1El = document.querySelector('player-one');
var player1Meta = {
  x: 20,
  y: 20
}
function updatePlayer(el, meta){
  el.style.left = meta.x + 'px';
  el.style.top = meta.y + 'px';
}
document.addEventListener('keyup', function(e){
  switch(e.which){
    case 65:
      player1Meta.x -= 10;
      break;
    case 68:
      player1Meta.x += 10;
      break;
    case 87:
      player1Meta.y -= 10;
      break;
    case 83:
      player1Meta.y += 10;
      break;
    default:
      break;
  }
  updatePlayer(player1El, player1Meta);
});
game-world{
  width:500px;
  height:400px;
  background:#333;
  display:block;
}
player-one,player-two{
  position:absolute;
  display:block;
  border-radius:50%;
  width:25px;
  height:25px;
}
player-one{
  background:#acf;
  left:20px;
  top:20px;
}
player-two{
  background:#fac;
  left:200px;
}
<game-world>
  <player-one></player-one>
  <player-two></player-two>
</game-world>

您的代码中有许多错误

  1. 左必须有一个单位

var move = 10;
window.addEventListener('keydown', function(e) {
  var a = String.fromCharCode(e.which);
  if (a == 'A') {
    document.getElementById("player").style.left = move + "px";
    move += 10;
  };
});
#player {
  width: 10px;
  height: 10px;
  background: red;
  position: absolute;
}
<div id="wrapper">
  <div id="player"></div>
  <div id="player2"></div>
</div>

相关内容

最新更新