В настоящее время я создаю базовый автогонщик javascript, в котором автомобиль является элементом HTML tr, размещенным в td. Я хочу, чтобы при нажатии клавиши «e» игрок переместился, и если нажата клавиша «d», игрок 2 переместится. Я хочу сделать это, используя eventListener, чтобы при нажатии клавиши машина переместится с исходного элемента td на следующий td-элемент и удалит автомобиль из предыдущего. Это заставит его выглядеть так, как будто автомобиль двинулся. Я не знаю, как перемещать этот элемент с помощью нажатия клавиши, но мой код ниже. Спасибо за помощь!Переместить элемент html td с помощью JavaScript
document.addEventListener('DOMContentLoaded', function() {
//run the code
\t function move = function(player){
\t \t /*
\t \t psuedo code:
\t \t
\t \t if Keypressed = "E"
\t \t then move first car forward
\t \t else d move second car forward
\t \t
\t \t if player1 has moved to the end
\t \t then end the game
\t \t
\t \t else for player 2
\t \t
\t \t set a var to add up the total moves, user can then easily adapted the length of the road and have it match
\t \t the var total.
\t \t */
\t }
\t function keyPress = function(e){
\t \t if (e.charCode == "e"){
\t \t \t //move player one
\t \t }
\t \t else if (e.charCode == "d"){
\t \t \t //move player 2
\t \t }
\t \t else{
\t \t \t alert("Invalid key stroke");
\t \t }
\t }
\t
})
.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>
\t <table class="racer_table">
\t <tr id="player1_strip">
\t \t <td class="active"></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t </tr>
\t <tr id="player2_strip">
\t \t <td class="active"></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t \t <td></td>
\t </tr>
\t </table>
</body>
</html>
Прохладный ответ, однако мой компилятор продолжает возвращать «Uncaught ReferenceError: $ не определен» для строки: var active = $ ("# player1_strip"). Children (". Active"); Знаете ли вы, почему это может быть? Спасибо – James
не понял, что у вас нет jquery, просто javascript. здесь приведен пример работы jquery: http://codepen.io/tylert/pen/JGwQWv – TylerT