Use KeyCode to press WASD in the browser to make the graphics move

How to make the graph move up, down, left, and right by pressing the WASD four keys in the browser?

In fact, it is very simple, using the keyCode method can be achieved.

First put a div in the html:

1 <div id="ball" style="left: 0px;top: 0px"></div>

Set the inline css style in the div. As for why you want to set the inline style, I will explain it later.

css part:

1 <style>
2     div{
3         height: 100px;
4         width: 100px;
5         background: #0ff;
6         border-radius: 50px;
7         position: absolute;
8     }
9 </style>

Because the left and top properties are set in the div, absolute positioning must be set

Then the next part is the js part:

1 var key={
2         W:87,S:83,A:65,D:68 
3     }

Declare a variable key to store the Unicode codes of the four keys of WASD.

 1 function keymove(e){
 2             var ball=document.getElementById('ball');
 3             var left=parseInt(ball.style.left);
 4             var top=parseInt(ball.style.top);
 5             switch(e.keyCode){
 6                 case key.W:
 7                     ball.style.top=top-2+'px';
 8                 break;
 9                 case key.S:
10                     ball.style.top=top+2+'px';
11                 break;    
12                 case key.A:
13                     ball.style.left=left-2+'px';
14                 break;    
15                 case key.D:
16                     ball.style.left=left+2+'px';
17                 break;    
18             }
19         }
20         document.onkeydown=keymove;

Write a function keymove parameter as e (any English can be used), because the attribute value of the element is a string, so you need to use the parseInt method to convert it to the int data type, and then use a series of judgment statements, if or switch Statements are fine, I use switch here because it is more convenient.

The return value of parameter name.keyCode is the Unicode code value corresponding to the user pressing the keyboard key.

Finally, the function is called, and the function is executed when the onkeydown event is triggered. The keyCode can also be used in the onkeypress and onkeyup events.

Finally, to answer why the left and top properties use inline rather than embedded methods, here are some knowledge points:

In js, element refers to the dom object obtained by js,

And element.style represents the inline style obtained by js. If the object has no inline style, it is an empty object.

Of course, there are other ways to obtain object styles that can obtain non-inline styles, but if you use the element.style method to obtain styles, the styles defined by non-inline methods cannot be obtained.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325320217&siteId=291194637