```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
#div1 {
width: 40px;
height: 40px;
position: absolute;
background: orange;
transform: rotate(0deg);
z-index: 1;
}
.pd {
width: 5px;
height: 15px;
border-radius: 50%;
position: absolute;
background: #f06;
}
</style>
</head>
<body>
<div id="div1" style="top:350px;left:100px"></div>
</body>
</html>
<script>
//按住鍵盤的上下左右箭頭? 控制div的移動?
// 按住 空格鍵? 創(chuàng)建子彈 并發(fā)射子彈
var tank = document.getElementById("div1");
document.onkeydown = function (eve) {
var e = eve || event;
var code = e.keyCode || e.which || e.charCode;
var l = parseInt(tank.style.left);
var t = parseInt(tank.style.top);
if (code == 37) {
l = l < 0 ? 0 : l;//防止div跑出瀏覽器左邊框
tank.style.left = l - 5 + "px";
}
if (code == 38) {
t = t < 0 ? 0 : t;//防止div跑出瀏覽器上邊框
tank.style.top = t - 5 + "px";
}
if (code == 39) {
l = l > document.documentElement.clientWidth - 45 ? document.documentElement.clientWidth - 45 : l;//防止div跑出瀏覽器右邊框
tank.style.left = l + 5 + "px";
}
if (code == 40) {
t = t > document.documentElement.clientHeight - 45 ? document.documentElement.clientHeight - 45 : t;//防止div跑出瀏覽器下邊框
tank.style.top = t + 5 + "px";
}
if (code == 32) {
var pd = document.createElement('div');
document.documentElement.appendChild(pd);
pd.className = "pd";
pd.style.top = tank.style.top;
pd.style.left = parseInt(tank.style.left) + 17 + "px";
var timer = setInterval(function () {
pd.style.top = parseInt(pd.style.top) - 4 + "px";
if (parseInt(pd.style.top) < 0) {
//子彈跑出瀏覽器上邊框,就刪除這個pd元素節(jié)點
document.documentElement.removeChild(pd);
clearInterval(timer);
}
}, 10)
}
}
</script>
```
這是運用js實現(xiàn)的簡易功能;并沒有實現(xiàn)游戲效果。