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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM