发射子弹小案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<style>
.box {
width: 600px;
height: 800px;
margin: 100px auto;
background-color: blue;
position: relative;
}
.box .car {
width: 50px;
height: 50px;
background-color: pink;
position: absolute;
top: 0;
left: 0;
}
.box .dian {
width: 10px;
height: 10px;
background-color: #ffffff;
border-radius: 50%;
position: absolute;
top: 0;
left: 0;
}
</style>
<div class="box">
<div class="car"></div>
<!-- <div class="dian"></div> -->
</div>
<script>
(function() {
var car = document.querySelector('.car'); //移动模块
var box = document.querySelector('.box');
var x; // 移动模块到左边的距离
var y; // 移动模块到上面的距离
var iddian; // 定时器小点生成
var idMove; // 定时器小点移动
var dian_list; // 所有的小点
box.addEventListener('mousemove',function(event) {
x = event.pageX - box.offsetLeft - 25;
y = event.pageY - box.offsetTop - 25;
if(x < 0) {x = 0}
else if(x > 550) {x = 550}
if(y < 0) {y = 0}
else if(y > 750) (y = 750)
car.style.top = y + 'px';
car.style.left = x + 'px';
})
getdian();
function getdian() {
// 定时生成生成小子弹
setInterval(() => {
var dian = document.createElement('div');
box.appendChild(dian)
dian.className = 'dian';
dian.style.top = y - 10 + 'px';
dian.style.left = x + 20+ 'px';
}, 200);
// 所有的小子弹都定时器-5
dianMOve()
function dianMOve() {
setInterval(() => {
dian_list = document.querySelectorAll('.dian');
for(var i = 0; i < dian_list.length; i++) {
run(dian_list[i]);
}
}, 10);
}
function run(dian) {
var y_top = parseInt(window.getComputedStyle(dian,null).top);
if(y_top < 0) {
dian.remove();
}
y_top -= 5;
dian.style.top = y_top + 'px';
}
}
})()
</script>
</body>
</html>