In fact, this example uses two core times of js, keyboard event onkeydown, and periodic execution event setInterval.
Realize the effect
When a keyboard key is pressed, the characters on the web page realize the corresponding action, achieving the effect of using the keyboard to control the movement
Implementation steps
1. The function of booking key value:
w: Upward
s: Down
a: Left
d: to the right
Space: Stop
2. After booking the key value, you must be able to capture the key event and determine which key the user is pressing?
You can use onkeydown to capture keyboard events
You can use event.keyCode to obtain key-value codes
3. Replace the picture with setInterval cycle execution event
Replace the picture to achieve task movement effect
But be careful to use clearInterval to execute, otherwise it will get faster and faster
Sample code:
<html><head><meta charset="utf-8" /><title>character walks</title></head><body onkeydown="show()"><ul style="postion:absolute;border:1px solid #999;list-style:none;width:150px;padding:20px;background:#ffffef;"><li>w:upward</li><li>s:downward</li><li>a: left</li><li>d:right</li><li>space:stop</li><li>s:stop</li><li>s href="//www.VeVB.COM">Wulin.com</a></u></li></ul><div style="position:absolute;top:0;left:0" id='di'><img src="//files.VeVB.COM/file_images/article/201408/201482791327688.gif?201472791345" id="img"></div><script>var img1='//files.VeVB.COM/file_images/article/201408/201482791656841.gif?201472791722';var img2='//files.VeVB.COM/file_images/article/201408/201482791327688.gif?201472791345';var x=0;var y=0;var xs=0;var ys=0;var flag=true;var zq=null;function ks(){zq=setInterval(function(){var s=document.getElementById('img');var str=s.src;var area=document.getElementById('di');var xpos=parseInt(area.style.left);var ypos=parseInt(area.style.top);x=x+xs;y=y+ys;area.style.left=x;area.style.top=y;var pos=str.lastIndexOf('/')+1;var hz=str.substr(pos);if(hz==img1){s.src=img2;}else{s.src=img1;}},50);}ks();function show(){var sz=window.event.keyCode;switch(sz){case 87:img1='//files.VeVB.COM/file_images/article/201408/ren_h_1.gif';img2='//files.VeVB.COM/file_images/article/201408/ren_h_2.gif';ys=-5;xs=0;break;case 65:img1='//files.VeVB.COM/file_images/article/201408/ren_l_1.gif';img2='//files.VeVB.COM/file_images/article/201408/ren_l_2.gif';xs=-5;ys=0;break;case 68:img1='//files.VeVB.COM/file_images/article/201408/ren_r_1.gif';img2='//files.VeVB.COM/file_images/article/201408/ren_r_2.gif';xs=5;ys=0;break;case 83:img1='//files.VeVB.COM/file_images/article/201408/ren_q_1.gif';img2='//files.VeVB.COM/file_images/article/201408/ren_q_2.gif';ys=5;xs=0;break;case 32: if(flag){ clearInterval(zq); flag=false; break; }case 13: if(!flag){ ks(); flag=true;break; }}}</script></body></html>