2017-05-05 148 views
2
<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

你可以分享你的JS代码?你尝试过的一个(如果你)。 –

回答

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 
} 

}); 
+0

它不使球移动,它只显示警告框,当我点击钥匙圈 – amir

+2

我留下了评论,所以你实现的运动,我给你解决方案如何检测键盘箭头按下。如果你想让我解决这个问题,你可以发布你的移动球码。 –

相关问题