如何使用键盘左/右/上/下移动球?

时间:2017-05-05 16:09:09

标签: javascript html css

<html>
<head>
    <link rel="stylesheet" href="new 1.css">
    <script src="new 1.js">
    </script>
</head>
<body>
    <button id=redButton type="button" onclick="TurnBallRed()">set ball color red</button>
    <button id=blueButton type="button" onclick="TurnBallBlue()">set ball color blue</button>
    <button id=greenButton type="button" onclick="TurnBallGreen()">set ball color green</button>
    <div id="container">
        <div id="ball">
        </div>
    </div>
</body>

如何使用键盘左/右/上/下移动球?

我不想使用jQuery,只使用JavaScript代码。

我尝试使用kcode。

谢谢。

1 个答案:

答案 0 :(得分:4)

好的,首先你需要在按下键盘键时添加一个新的事件监听器,你在代码中做了一些事情。对于此步骤,您可以执行以下操作:

document.addEventListener('keydown', function(event) {
alert('keyboard is being smashed');
});

接下来,您应该获得用户按下的键,以便您可以执行操作。我在this link的w3school上学到了这一点。对于第二步,您可以执行以下操作:

if(event.keyCode == 37) {
    alert('Left arrow of keyboard was smashed');
}
else if(event.keyCode == 38) {
    alert('Up arrow of keyboard was smashed');
}
else if(event.keyCode == 39) {
    alert('Right arrow of keyboard was smashed');
}
else if(event.keyCode == 40) {
    alert('Down arrow of keyboard was smashed');
}

最终代码:

document.addEventListener('keydown', function(event) {
if(event.keyCode == 37) {
    alert('Left arrow of keyboard was smashed');
    //move the ball to left
}
else if(event.keyCode == 38) {
    alert('Up arrow of keyboard was smashed');
    //move the ball to up
}
else if(event.keyCode == 39) {
    alert('Right arrow of keyboard was smashed');
    //move the ball to right
}
else if(event.keyCode == 40) {
    alert('Down arrow of keyboard was smashed');
    //move the ball to down
}

});
相关问题