Presumably everyone has played a web game. With the popularity of HTML5, browser + cloud Web App has become the future trend. There are many effects that can be achieved without JavaScript. So if you want to do web development, JavaScript must learn.
The web game is how to achieve the character's mobile effect, today to share a very basic simple method.
As follows: Click on the top button, the mob starts to move to the right.
The Html+css section is very simple. It's not much to say. It is important to note that the image is to use absolute positioning.
So how do you move the picture to the right?
Since the picture has the position property, we just need to change its property value. For example, if we click the button, the villain will go to the right 20px, then we just need to add 20px to its left, that is to say img.style.left+20. The principle is very simple.
But one problem is that pixels are units (px), how do we calculate them? So we need to get rid of its units. How to go? Check the manual!
Found in the JS string object has a method called substr (), you can intercept the string to the specified position of the character. substr (initial position, specified length).
For example a= "ABCDEFG", if we only Want "CD", then only need to intercept a.substr (2,2) to get "CD."
Thus we can get a string without a unit. Simply call the parseint method to convert it to an integer.
The following is all the code, or very interesting.
[HTML]View Plaincopy
- <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
- <html xmlns= "http://www.w3.org/1999/xhtml" xml:lang="en">
- <head>
- <meta http-equiv= "content-type" content="Text/html;charset=utf-8">
- <title>document</title>
- <script type="Text/javascript">
- function moveimg () {
- this.move=Function (dir) {
- if (dir==1) {
- var tomove=document.getElementById ("img");
- var goright=tomove.style.left;//get the distance from the current left
- goright=parseint (Goright.substr (0,goright.length-2))//convert distance to a number that can be calculated
- tomove.style.left=goright+20+ "px";//20px per walk
- }
- }
- }
- var myimg=New moveimg ();
- </Script>
- </head>
- <body>
- <p><input type="button" value="go right!!! " onclick=" Myimg.move (1) "></P>
- <div>
- <img style="position:absolute;left:0px;width:80px;" id="img" src="http://tangmaru.com/content/uploadfile/201309/73b21379867707.png"/>
- </div>
- </body>
- </html>
But I have a question, the above code I use inline method to set the CSS method, you can access its properties in JS.
But if I use embedded, how to access its Left property in JS? If anyone knows, please do not hesitate to enlighten! Thank you!
Web front-end development learning----4. Using JavaScript to achieve the mobile effect of web games