Just learning JS event This together, see the video tutorial taught to do aircraft in the War Aircraft Movement program:
varOdiv = document.getElementById ("Div1"); varTimer =NULL; varleft =false; varright =false; vartop =false; varBottom =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) {varEV = EV | |event; varKeyCode =Ev.keycode; Switch(keycode) { Case37:left =true; Break; Case38:top =true; Break; Case39:right =true; Break; Case40:bottom =true; Break; }} Document.onkeyup=function(EV) {varEV = EV | |event; varKeyCode =Ev.keycode; Switch(keycode) { Case37:left =false; Break; Case38:top =false; Break; Case39:right =false; Break; Case40:bottom =false; Break; } }
This code can only move up and down in four directions, but not on the left, left, and so on, I looked for a solution on the internet, one of which is to put all the keys pressed down the keycode into an array, and then by judging the values in the array to decide which action to perform
<script>varkeycodearry=[]; Document.onkeydown=function(EV) {varoevent=ev| |event; KeyCode=Oevent.keycode; Keycodearry=Addkeycodearry (Keycode,keycodearry); Console.log (Keycodearry); } document.onkeyup=function(EV) {varoevent=ev| |event; KeyCode=Oevent.keycode; Keycodearry=Deletkeycodearry (Keycode,keycodearry); Console.log (Keycodearry); } functionAddkeycodearry (Num,arr) {varCheck=0; for(vari=0;i<arr.length;i++) { if(arr[i]==num) {Check=1; } } if(check==0) {arr.push (num); } returnarr; } functionDeletkeycodearry (Num,arr) { for(vari=0;i<arr.length;i++) { if(arr[i]==num) {Arr.splice (i,1); } } returnarr; } </script>
JS Judge Press two keys at the same time