javascript - 使用 JavaScript 移动 html td 元素

标签 javascript html css

我目前正在创建一个基本的 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/

相关文章:

javascript - 为什么我的下拉菜单在 div 中不起作用?

HTML anchor 标记占用整行

html - 位置固定不适用于谷歌地图

javascript - 有没有办法制作不可编辑的跨度?

javascript - 如何从包含完整网页代码的变量中收集特定 <span> 的值

javascript - React 和 MobX - 用户离开现有页面时的确认对话框

javascript - 当我更改元素的顺序时,元素 "jerk"回到右侧

javascript - 带动画的 Angular 显示/隐藏

javascript - Safari 移动文本输入问题

javascript - Contenteditable--编辑时改变背景颜色