如何将<img/>移至使用箭头键?

时间:2017-05-23 11:44:59

标签: javascript jquery

我有一个10x10的表,其中一个单元格中有一个图像。这是代码。

$(document).ready(function(){
            var allTds = $("td")
            for(i in allTds){
                if(Math.random() < 0.4){
                    allTds.eq(i).addClass("block")
                }
            }
            var allOpen = $("td:not(.block)")
            var selectLoc1 = Math.floor(Math.random()*allOpen.length)
            var selectLoc2 = Math.floor(Math.random()*allOpen.length)
            var image = $("<img>")
            image.attr("src", "pawn.png")
            allOpen.eq(selectLoc1).append(image)
            allOpen.eq(selectLoc2).addClass("goal")
})

当用户按下箭头键时,图像必须根据按下的箭头键从td移动到td。我如何在我将要放入的代码中实现这一点?感谢。

2 个答案:

答案 0 :(得分:2)

您必须检测按键事件,并根据按下的按键将图像移动到相应的按钮。

例如,假设imageCellRow, imageCellColumn是图像的当前位置。然后使用以下逻辑将图像移动到新位置。

switch(arrowKey) {
    case leftArrow:
        console.log("left");
        imageCellColumn--;
        break;
    case rightArrow:
        console.log("right");
        imageCellColumn++;
        break;
    case upArrow:
        console.log("up");
        imageCellRow--;
        break;
    case downArrow:
        console.log("down");
        imageCellRow++;
        break;
}

imageCellRow = (imageCellRow + height) % height;
imageCellColumn = (imageCellColumn + width) % width;

现在您拥有了图片的新位置,剩下的就是删除旧图片并将其添加到新位置。

此处的工作示例(单击生成的表格,然后按箭头键)

&#13;
&#13;
$(function () {
	//console.log("started");
	var tableWidth = 5;
	var tableHeight = 5;
	var imageUrl = "https://cdn.pixabay.com/photo/2013/07/12/15/02/penguin-149275_960_720.png";
	var image = $("<img src='" + imageUrl + "'>");
	
	generateTable(tableWidth, tableHeight);
	addImageToCell($("table"), image, 0, 0);
	
	/* <Image movement logic> */
	(function () {
		var table = $("table");
		var width = table.find("tr:first td").length;
		var height = table.find("tr").length;
		//console.log("table dim: " + width + "," + height);

		//Initial image cell
		var imageCellRow = 0;
		var imageCellColumn = 0;
			
		var leftArrow = 37;
		var upArrow = 38;
		var rightArrow = 39;
		var downArrow = 40;
		
		$(document).keydown(function (e) {
			//Remove image from current Cell
			table.find("tr:eq(" + imageCellRow + ") td:eq(" + imageCellColumn +") img").remove();
			
			switch(e.which) {
				case leftArrow:
					//console.log("left");
					imageCellColumn--;
					break;
				case rightArrow:
					//console.log("right");
					imageCellColumn++;
					break;
				case upArrow:
					//console.log("up");
					imageCellRow--;
					break;
				case downArrow:
					//console.log("down");
					imageCellRow++;
					break;
			}
			imageCellRow = (imageCellRow + height) % height;
			imageCellColumn = (imageCellColumn + width) % width;
			
			addImageToCell(table, image, imageCellRow, imageCellColumn);
		});
	})();
	/* <Image movement logic /> */
	
	//Generates table with given dimensions
	function generateTable(width, height) {
		var table = "<table>";
		
		for(var j = 0; j < height; j++) {
			table += "<tr>";
			for(var i = 0; i < width; i++) {
				table += "<td/>";
			}
			table += "</tr>";
		}
		
		table += "</table>";
		
		$("body").append(table);
	}
	
	function addImageToCell(table, image, cellRow, cellColumn) {
		table.find("tr:eq(" + cellRow + ") td:eq(" + cellColumn +")").append(image);
	}
});
&#13;
<html>
<head>
	<script
	  src="https://code.jquery.com/jquery-3.2.1.min.js"
	  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
	  crossorigin="anonymous"></script>
	<script src="app.js"></script>
	
	<style>
		td {
			width: 50px;
			height: 50px;
			border: 1px solid black;
		}
		td img {
			width: 45px;
			height: 45px;
		}
	</style>
</head>
<body>

</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这仅仅是背景改变和走过桌子的一个例子...... 我认为其余的很简单......

&#13;
&#13;
  <!doctype html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Table key´s</title>
    <style>
      td{width:20px;height:20px;background:#ddd;}
      tr:nth-child(5) td:nth-child(5){background:#f00;}
    </style>
  </head>
  <body>
    <div id="tableContainer">
    </div>
    <script>    
      var row=col=5,max=10;
      tableContainer.innerHTML = '<table>'+('<tr>'+'<td>'.repeat(max)).repeat(max)+'</table>';
      window.addEventListener("keyup", function(e){
        var colDiff, rowDiff;
        var keyMap = new Map([[37,[-1,0]],[38,[0,-1]],[39,[1,0]],[40,[0,1]]]);
        if (keyMap.has(e.keyCode)){
          document.querySelector(`tr:nth-child(${row}) td:nth-child(${col})`).style.background='#ddd';
          [colDiff,rowDiff]=keyMap.get(e.keyCode);
          row+=rowDiff;
          col+=colDiff;
          row = (row>max) ? max : (row < 1) ? 1 : row;
          col = (col>max) ? max : (col < 1) ? 1 : col;
          document.querySelector(`tr:nth-child(${row}) td:nth-child(${col})`).style.background='#f00';
        }
      }) 
    </script>
  </body>
  </html>
&#13;
&#13;
&#13;

你也可以使用表格对象......

&#13;
&#13;
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Table key´s</title>
  <style>
    td{width:20px;height:20px;background:#ddd;}
  </style>
</head>
<body>
  <div id="tableContainer">
  </div>
  <script>    
    var aktRow=aktCol=4,max=9;
    tableContainer.innerHTML = '<table id="mt">'+('<tr>'+'<td></td>'.repeat(max+1)+'</tr>').repeat(max+1)+'</table>';
    mt.rows[aktRow].cells[aktCol].style.background='#f00';
    window.addEventListener("keyup", function(e){
      var colDiff, rowDiff;
      var keyMap = new Map([[37,[-1,0]],[38,[0,-1]],[39,[1,0]],[40,[0,1]]]);
      if (keyMap.has(e.keyCode)){
        mt.rows[aktRow].cells[aktCol].style.background='#ddd';
        [colDiff,rowDiff]=keyMap.get(e.keyCode);
        aktRow+=rowDiff;
        aktCol+=colDiff;
        aktRow = (aktRow>max) ? max : (aktRow < 0) ? 0 : aktRow;
        aktCol = (aktCol>max) ? max : (aktCol < 0) ? 0 : aktCol;
        mt.rows[aktRow].cells[aktCol].style.background='#f00';
      }
    }) 
  </script>
</body>
</html>
&#13;
&#13;
&#13;