<!DOCTYPE html>
<html onkeydown="run(event)">
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#main{
300px;height:300px;
border:1px solid blue;
}
#tank{
50px;height:50px;
border:1px solid red;
}
</style>
</head>
<body>
<div id="main"><div id="tank" style="margin-top:0px;margin-left:0px;"></div></div>
<script type="text/javascript">
var tank=document.getElementById("tank");
var zd=[];
function run(e){
//按下了哪个键
//alert(e.keyCode);
switch(e.keyCode){
case 37:
left();
break;
case 38:
up();
break;
case 39:
right();
break;
case 40:
down();
break;
case 32:
fire();
break;
default:
break;
}
}
function up(){
tank.style.marginTop=parseInt(tank.style.marginTop)-20+"px";
}
function down(){
tank.style.marginTop=parseInt(tank.style.marginTop)+20+"px";
}
function left(){
tank.style.marginLeft=parseInt(tank.style.marginLeft)-20+"px";
}
function right(){
tank.style.marginLeft=parseInt(tank.style.marginLeft)+20+"px";
}
function fire(){
//制造炮弹
var obj=document.createElement("div");
obj.style.width="10px";
obj.style.height="10px";
obj.style.backgroundColor="red";
obj.style.position="absolute";
obj.style.top=tank.style.marginTop;
obj.style.left= parseInt(tank.style.marginLeft) +25 +"px" ;
main.appendChild(obj);//将子弹加入到tank中
zd[zd.length]=obj;
}
//检测,让所有的子弹飞!!
setInterval(function(){
for(var i in zd){
zd[i].style.top=parseInt(zd[i].style.top) -5 +"px";
}
},50);
</script>
</body>
</html>