1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"/> 5 <title>JavaScript实例</title> 6 <style> 7 #did{width:500px;height:500px;background-color:#ddd;position:relative;overflow:hidden;} 8 #gid{width:50px;height:60px;background-color:red;position:absolute;top:150px;left:100px;} 9 #p0,#p1,#p2,#p3,#p4{width:5px;height:10px;background-color:#000;position:absolute;} 10 </style> 11 </head> 12 <body> 13 <h2>JavaScript实例:键盘事件</h2> 14 <div id="did"> 15 <div id="p0" style="display:none;"></div> 16 <div id="p1" style="display:none;"></div> 17 <div id="p2" style="display:none;"></div> 18 <div id="p3" style="display:none;"></div> 19 <div id="p4" style="display:none;"></div> 20 21 <div id="gid"></div> 22 </div> 23 <script type="text/javascript"> 24 var gid = document.getElementById("gid"); 25 window.document.onkeydown = function(ent){ 26 //获取兼容的事件对象 27 var event = ent || window.event; 28 //alert(event.keyCode); 29 //根据键盘值执行对应操作 30 switch(event.keyCode){ 31 case 37: //左方向键 32 gid.style.left = Math.max(0,gid.offsetLeft-5)+"px"; 33 break; 34 case 38: //上方向键 35 gid.style.top = Math.max(0,gid.offsetTop-5)+"px"; 36 break; 37 case 39: //右方向键 38 gid.style.left = Math.min(450,gid.offsetLeft+5)+"px"; 39 break; 40 case 40: //下方向键 41 gid.style.top = Math.min(440,gid.offsetTop+5)+"px"; 42 break; 43 case 32: //空格键 44 shoot(gid.offsetLeft+24,gid.offsetTop); //发射炮弹 45 break; 46 } 47 } 48 49 //发射炮弹方法 50 function shoot(x,y){ 51 //遍历所有炮弹 52 for(var i=0;i<5;i++){ 53 var p = document.getElementById("p"+i); 54 //判断炮弹是否可用 55 if(p.style.display=="none"){ 56 p.style.top = y+"px"; 57 p.style.left = x+"px"; 58 p.style.display = "block"; 59 //没有return 只能发射一枚 60 return; 61 } 62 } 63 } 64 65 //游戏主线程 66 function running(){ 67 //负责移动可见炮弹 68 for(var i=0;i<5;i++){ 69 var p = document.getElementById("p"+i); 70 //判断炮弹是否可用 71 if(p.style.display=="block"){ 72 p.style.top = p.offsetTop-5+"px"; 73 //回收出了屏幕的炮弹 74 if(p.offsetTop<-10){ 75 p.style.display = "none"; 76 } 77 } 78 } 79 80 setTimeout("running()",33); 81 } 82 83 running(); 84 </script> 85 </body> 86 </html>
上下左右键移动,空格发射子弹