JS中的键盘事件

时间:2019-02-20
本文章向大家介绍JS中的键盘事件,主要包括JS中的键盘事件使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		#box{width: 100px;height: 100px;border-radius: 50%;background: red;position: absolute;left: 0;top: 0;}
	</style>
</head>
<body>
	<div id="box"></div>
	<script type="text/javascript">
		/*
			onkeydown  onkeypress  onkeyup
			
			keyCode  :键码

			点击上下左右  实现小球向对应方向移动
		*/

		var o=document.getElementById('box');

		document.onkeydown=function (e) {
			e=e||window.event;
			console.log(e);
			switch(e.keyCode){
				case 37:
					// console.log('左');
					moveHor(-10);
				break;
				case 38:
					// console.log('上');
					moveVer(-10);
				break;
				case 39:
					// console.log('右');
					moveHor(10);
				break;
				case 40:
					// console.log('下');
					moveVer(10);
				break;
				default:
					console.log('其他');
				break;
			}
		};

		function moveHor(speed){
			o.style.left=o.offsetLeft+speed+'px';
		}

		function moveVer(speed){
			o.style.top=o.offsetTop+speed+'px';
		}
	</script>
</body>
</html>