js代码实现模仿推箱子

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>

	<body>
		<img src="1.jpg" style="height: 100px;width: 100px; position: absolute;left: 0px; top: 0px;" id="img" />
		<script type="text/javascript">
			var img = document.getElementById("img");
			img.left = 0;
			img.top = 0;

			function move() {
				console.log(event.keyCode);
				if(event.keyCode == 37 || event.keyCode == 65) {

					img.left -= 80;

				}

				if(event.keyCode == 38 || event.keyCode == 87) {

					img.top -= 80;

				}

				if(event.keyCode == 39 || event.keyCode == 68) {

					img.left += 80;

				}
				if(event.keyCode == 40 || event.keyCode == 83) {

					img.top += 80;

				}
				img.style.left = img.left + "px";
				img.style.top = img.top + "px";

			}
			document.onkeydown = move;
		</script>

	</body>

</html>

你可能感兴趣的:(js)