JavaScript
x
18
18
1
function control()
2
{
3
var ship = document.getElementById("ship");
4
document.onkeydown = function(e) {
5
switch (e.keyCode) {
6
case 38:
7
ship.style.top += "5%";
8
break;
9
case 40:
10
ship.style.top -= "5%";
11
break;
12
default:
13
break;
14
}
15
}
16
}
17
setInterval(control,1000);
18
This code is not working.
The object I’m trying to move is not moving when I’m pressing the Up & Down Arrow Key.
Advertisement
Answer
You should do something like that:
JavaScript
1
16
16
1
const ship = document.getElementById("ship");
2
document.onkeydown = function (e) {
3
let winHeigth = window.innerHeight;
4
let top = ship.style.top;
5
switch (e.code) {
6
case "ArrowUp":
7
ship.style.top = (Number(top.substring(0, top.length - 2)) - (winHeigth / 20)) + "px";
8
break;
9
case "ArrowDown":
10
ship.style.top = (Number(top.substring(0, top.length - 2)) + (winHeigth / 20)) + "px";
11
break;
12
default:
13
break;
14
}
15
}
16
The position attribute of the “ship” must be like “relative”. By the way, e.keyCode is deprecated, you can use e.code instead ^^