js之键盘控制div移动

onkeydown/onkeyup

onkeydown事件若按键不抬起,那么会连续触发
例如敲击键盘a,按住:aaaaaaaaaaaaaaaa,
第一个和第二个a中间有个明显的停顿时间间隔,有时候需要去除,例如游戏。
思考:如何去除停顿问题?提示:像汽车,发动机负责动力,方向盘负责方向,类似这种原理,div的移动功能可以交给发动机(定时器)去做,方向交给方向盘(键盘事件)去做。
一个div

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			div{
				width: 100px;
				height: 100px;
				background: red;
				position: absolute;
				top: 8px;
				left: 8px;
				
			}
		</style>
		<script type="text/javascript">
			//因为持续按键那么第一下和第二下有时间间隔;比如a aaaaaaaa  ,所以用定时器来做加减
			//keyCode 值 左上右下 37--40
			window.onload=function(){
				var oDiv=document.getElementsByTagName('div')[0];
				var json={'left':'false','top':'false','right':'false','bottom':'false'};
				document.onkeydown=function(ev){
					var ev=ev || event;
					if(ev.keyCode==37){
						json['left']=true;
						
					}
					if(ev.keyCode==38){
						json['top']=true;
					}
					if(ev.keyCode==39){
						json['right']=true;
					}
					if(ev.keyCode==40){
						json['bottom']=true;
					}
				}
				document.onkeyup=function(){
					var ev=ev || event;
					if(ev.keyCode==37){
						json['left']=false;
					}
					if(ev.keyCode==38){
						json['top']=false;
					}
					if(ev.keyCode==39){
						json['right']=false;
					}
					if(ev.keyCode==40){
						json['bottom']=false;
					}
				}
				setInterval(function(){
					if(json['left']==true){
						oDiv.style.left=oDiv.offsetLeft-10+'px';
					}
					if(json['top']==true){
						oDiv.style.top=oDiv.offsetTop-10+'px';
					}
					if(json['right']==true){
						oDiv.style.left=oDiv.offsetLeft+10+'px';
					}
					if(json['bottom']==true){
						oDiv.style.top=oDiv.offsetTop+10+'px';
					}
				},30);
			}
		</script>
	</head>
	<body>
		<div id="">
			
		</div>
	</body>
</html>

posted @ 2018-07-30 16:14  菜鸡变小鸟  阅读(3555)  评论(0编辑  收藏  举报