js 实现键盘控制方块移动

版权声明:https://blog.csdn.net/qq_37618797 https://blog.csdn.net/qq_37618797/article/details/82903914

需求:

在网页上有一个方块,我们需要键盘上下左右键控制方块的移动。

代码:

<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title>移动方块</title>
	</head>

	<body>
		<script type="text/javascript">
			/* 创建一个div */
			var div = document.createElement("div");
			/* 将div添加到网页中 */
			document.body.appendChild(div);
			/* 设置div的样式 */
			div.style.width = "100px";
			div.style.height = "100px";
			div.style.backgroundColor = "red";
			div.style.position = "absolute";
			div.style.top = "0";
			div.style.left = "0";
			/* 键盘按下事件 */
			document.onkeydown = function(e) {
				/* 方块移动的速度,即每按一次方块移动的像素,值越大移动速度越快 */
				var speed = 10;
				switch(e.which){
					// 上
					case 38:
					  div.style.top = parseInt(div.style.top) - speed + "px";
					  break;
					// 下
					case 40:
						div.style.top = parseInt(div.style.top) + speed + "px";
						break;
					// 左
					case 37:
						div.style.left = parseInt(div.style.left) - speed + "px";
						break;
					// 右
					case 39:
						div.style.left = parseInt(div.style.left) + speed + "px";
						break;
				}
			}	
		</script>
	</body>

</html>

猜你喜欢

转载自blog.csdn.net/qq_37618797/article/details/82903914