<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
body {
background: black;
}
#demo {
width: 100px;
height: 100px;
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
background: url(plane.png) 0 / cover;
}
.bullet {
width: 10px;
height: 10px;
background: gold;
border-radius: 10px 10px 0 0;
box-shadow: 2px 5px 10px #fff;
position: absolute;
}
</style>
</head>
<body>
<div id="demo"></div>
</body>
<script>
const KEY_CODE = {
W: 87,
S:83,
A:65,
D:68,
J:74,
ENTER:13
}
let demo = document.getElementById('demo')
window.onkeydown = function (e) {
switch (e.keyCode) {
case KEY_CODE.W:
demo.style.top = (demo.offsetTop - 10) + 'px'
break;
case KEY_CODE.S:
demo.style.top = (demo.offsetTop + 10) + 'px'
break;
case KEY_CODE.A:
demo.style.left = (demo.offsetLeft - 10) + 'px'
break;
case KEY_CODE.D:
demo.style.left = (demo.offsetLeft + 10) + 'px'
break;
case KEY_CODE.J:
fight()
break;
}
}
function fight() {
let bullet = document.createElement('div')
bullet.classList.add('bullet')
document.body.appendChild(bullet)
bullet.style.top = (demo.offsetTop - bullet.offsetHeight - 10) + 'px'//子弹的上距离为盒子基于父集的高度减去子弹自身的高度
//子弹的左距离为盒子距离父级元素的左边距离减去盒子本身宽度的一半再减去子弹自身距离的一半
bullet.style.left = demo.offsetLeft + (demo.offsetWidth / 2) - (bullet.offsetWidth / 2) + 'px'
}
setInterval(function () {
let bullets = document.getElementsByClassName('bullet')
for (let i = 0; i < bullets.length; i++) {
const bullet = bullets[i];
bullet.style.top = (bullet.offsetTop - 10) + 'px'
if (bullet.offsetTop < 50)
bullet.remove()
}
}, 20)
</script>
</html>