我目前正在创建一个基本的 javascript 赛车,其中汽车是一个放置在 td 中的 HTML tr 元素。我想要它,当我按下键“e”时,玩家 1 将移动,如果按下“d”键,玩家 2 将移动。我想通过使用 eventListener 来做到这一点,当按下键时,汽车将从其原始 td 元素移动到下一个 td 元素,并从前一个元素中移除汽车。这将使它看起来像汽车已经移动了。我不知道如何使用按键移动这个元素,但我的代码在下面。感谢您的帮助!
document.addEventListener('DOMContentLoaded', function() {
//run the code
function move = function(player){
/*
psuedo code:
if Keypressed = "E"
then move first car forward
else d move second car forward
if player1 has moved to the end
then end the game
else for player 2
set a var to add up the total moves, user can then easily adapted the length of the road and have it match
the var total.
*/
}
function keyPress = function(e){
if (e.charCode == "e"){
//move player one
}
else if (e.charCode == "d"){
//move player 2
}
else{
alert("Invalid key stroke");
}
}
})
.racer_table td {
background-color: white;
height: 50px;
width: 50px;
border: 5px;
border-color: black;
}
.racer_table td.active {
background-color: black;
}
<link rel="stylesheet" type = "text/css" href="style.css">
<script type="text/javascript" src="racer.js"> </script>
<body>
<table class="racer_table">
<tr id="player1_strip">
<td class="active"></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr id="player2_strip">
<td class="active"></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
最佳答案
我会为该对象设置一个 var,然后对同级对象使用 jquery 的“next”函数。
如果你添加这个按钮<button id="x1"/>
这将作为一个例子:
$("#x1").click(function() {
var active = $("#player1_strip").children(".active");
active.next().addClass("active");
active.removeClass("active");
});
关于javascript - 使用 JavaScript 移动 html td 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35327410/