Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm creating a game, the div with id "playerDiv" when I hit the space bar it should start going up but it doesn't. So I would like when I hit the space bar the div would go up high. could you help me? could you also report me the mistakes i made?

const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;

function jump() {
  let x = 420 + inc;
  player.top = player.top + x;
  inc++
  playerTimeOut = setTimeout(jump, 50);
}
window.addEventListener("keydown", checkKeyPress, false);

function checkKeyPress(key) {
  if (key.key === ' ') {
    jump();
  }
}
body {
  background-color: #222222;
}

#background {
  border: solid 2px #dddddd;
  width: 800px;
  height: 500px;
}

#playerDiv {
  background-color: #aaaaaa;
  width: 60px;
  height: 80px;
  position: relative;
  top: 420px;
  left: 10px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="style.css" rel="stylesheet" type="text/css">
  <title>Game</title>
</head>

<body>
  <div id="background">
    <div id="playerDiv">
    </div>
  </div>
</body>
<script src="script.js"></script>

</html>
question from:https://stackoverflow.com/questions/65853043/resolved-the-square-does-not-move-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
160 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're not passing the argument in addListener and you're not using correctly the top property, it belongs to style and needs unit , for example px

Also keyCode is deprecated, use key instead

const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;

function jump() {
  let x = 10 + inc;
  player.style.bottom = `${x}px`
  inc++
  console.log(player.style.bottom)
}

//window.addEventListener("keydown", e =>  e.key === "(Space Character)" ? jump() : '');

//For snippet only
jump()

setTimeout(() => jump(), 1000)
* {
  /* demo */
  box-sizing: border-box
}

body {
  background-color: #222;
}

#background {
  border: solid 2px #ddd;
  width: 800px;
  height: 500px;
  position: relative;
  /* demo */
  max-width: 100%
}

#playerDiv {
  background-color: #aaa;
  width: 60px;
  height: 80px;
  position: absolute;
  bottom: 0px;
  left: 10px;
}
<div id="background">
  <div id="playerDiv">
  </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...