键盘方向键移动元素

box1根据键盘上下左右按键移动,要记得给box1开启定位

<!DOCTYPE html>

<html>
	<head>
		<meta charset="UTF-8"/>
		<title></title>
		
		<style type="text/css">
			#box1{
				height: 100px;
				width: 100px;
				background-color: red;	
				position: absolute;			
			}
		</style>
		<script type="text/javascript">
			window.onload = function(){
								
				document.onkeydown = function(event){
					
					event = event || window.event;
					var speed = 10;
					/*37左  38上  39右 40下*/
	
					switch(event.keyCode){
						case 37:
							box1.style.left = box1.offsetLeft-speed+"px";
							
							break;
						case 38:
							box1.style.top = box1.offsetTop-speed + "px";
							break;
						case 39:
							box1.style.left =box1.offsetLeft+speed+"px";
							break;
						case 40:
							box1.style.top = box1.offsetTop+speed + "px";
							break;
						
					}
					
				};
			};
		
		</script>
	</head>
	
	<body>
		<div id="box1" ></div>
	</body>
</html>

用上面的方法在第一下和第二下之间会有卡顿,因此经过定时器改良,不会出现卡顿连贯的移动:

<!DOCTYPE html>

<html>
	<head>
		<meta charset="UTF-8"/>
		<title></title>
		
		<style type="text/css">
			#box1{
				height: 100px;
				width: 100px;
				background-color: red;	
				position: absolute;			
			}
		</style>
		<script type="text/javascript">
			window.onload = function(){
								
				var dir = 0;
				var speed = 10;
				//开启定时器控制移动
				setInterval(function(){
					
					
					/*37左  38上  39右 40下*/
	
					switch(dir){
						case 37:
							box1.style.left = box1.offsetLeft-speed+"px";
							
							break;
						case 38:
							box1.style.top = box1.offsetTop-speed + "px";
							break;
						case 39:
							box1.style.left =box1.offsetLeft+speed+"px";
							break;
						case 40:
							box1.style.top = box1.offsetTop+speed + "px";
							break;						
					}
				},30)
				
				document.onkeydown = function(event){					
					event = event || window.event;
					if(event.ctrlKey){
						speed=500;
					}else{
						speed=10;
					}
					dir = event.keyCode;
					
				};
				//当按键松开,元素不动
				document.onkeyup=function(){
					dir=0;
				}
				
			};
		
		</script>
	</head>
	
	<body>
		<div id="box1" ></div>
	</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值