刚刚在学习JS事件这一块儿,看到视频教程中教做飞机大战中飞机移动的程序:
var oDiv = document.getElementById("div1"); var timer = null; var left = false; var right = false; var top = false; var bottom = false; setInterval(function(){ if(left){ oDiv.style.left = oDiv.offsetLeft-10+"px"; }else if(top){ oDiv.style.top = oDiv.offsetTop-10+"px"; }else if(right){ oDiv.style.left = oDiv.offsetLeft+10+"px"; }else if(bottom){ oDiv.style.top = oDiv.offsetTop+10+"px"; } },50); document.onkeydown = function(ev){ var ev = ev || event; var keyCode = ev.keyCode; switch(keyCode){ case 37: left = true;break; case 38: top = true;break; case 39: right = true;break; case 40: bottom = true;break; } } document.onkeyup = function(ev){ var ev = ev || event; var keyCode = ev.keyCode; switch(keyCode){ case 37: left = false;break; case 38: top = false;break; case 39: right = false;break; case 40: bottom = false;break; } }
这段代码只能上下左右四个方向移动,而不能左上、左下这样移动,我找了一下网上的解决方案,其中有一个是把所有按下去的键的keyCode放到一个数组里,然后通过判断数组中的值来决定执行哪个动作
<script> var keyCodeArry=[]; document.onkeydown=function(ev){ var oEvent=ev||event; keyCode=oEvent.keyCode; keyCodeArry=addKeyCodeArry(keyCode,keyCodeArry); console.log(keyCodeArry); } document.onkeyup=function(ev){ var oEvent=ev||event; keyCode=oEvent.keyCode; keyCodeArry=deletKeyCodeArry(keyCode,keyCodeArry); console.log(keyCodeArry); } function addKeyCodeArry(num,arr){ var check=0; for (var i=0;i<arr.length;i++) { if (arr[i]==num) { check=1; } } if (check==0) { arr.push(num); } return arr; } function deletKeyCodeArry(num,arr){ for (var i=0;i<arr.length;i++) { if (arr[i]==num) { arr.splice(i,1); } } return arr; } </script>
时间: 2024-10-12 04:24:06