复习了一下原生JS,复习了一个飞机吐子弹的案例
知识点:
offsetY ---- 光标针对它所在元素的坐标
clientY ---- 光标距离可视区顶部的坐标
pageY ---- 光标距离页面顶部的坐标
鼠标的事件:onmousemove
思路:
1、先让飞机跟随鼠标移动
使用了鼠标的onmousemove事件,设置飞机的坐标
var x = event.clientX - div.offsetWidth /2;
2、设置子弹
间隔函数,每500ms创建出一个子弹
子弹的坐标,始终是相对于飞机的坐标,让子弹始终从飞机的中间射出。
bullet.style.left = div.offsetLeft + div.offsetWidth/2 - 10 + ‘px‘; bullet.style.top = div.offsetTop + ‘px‘
3、让子弹飞
设置间隔函数,每隔16ms,Top的坐标减少,这个时候要注意判断一下,当子弹的坐标 Top已经 < -100了,此时可以把子弹删除,否则会一直累加
for(var i = 0; i<bullets.length;i++){
currentTop = bullets[i].offsetTop;
if(currentTop < -100){
bullets[i].remove()
}else{
bullets[i].style.top = currentTop -5+ ‘px‘
}
}
<!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>
div.plane{
width:66px;
height:80px;
background:url(‘./img/own.png‘);
position:absolute;
top:0;
left:0;
}
.bullet{
width:20px;
height:20px;
border-radius: 50%;
background:green;
position:absolute;
left:0;
top:0;
}
</style>
</head>
<body>
<div class="plane"></div>
<script>
// 取得div,跟随鼠标移动
var div = document.querySelector(‘div.plane‘)
window.onmousemove = function(event){
// 获取鼠标坐标,并让其在正中间的位置
var x = event.clientX - div.offsetWidth/2;
var y = event.clientY - div.offsetHeight/2;
div.style.left = x + ‘px‘;
div.style.top = y + ‘px‘
}
function biuBiuBiu(){
// 创建子弹
var bullet = document.createElement(‘div‘);
bullet.className = ‘bullet‘;
bullet.style.left = div.offsetLeft + div.offsetWidth/2 - 10 + ‘px‘;
bullet.style.top = div.offsetTop + ‘px‘
// 上树
document.body.appendChild(bullet)
}
// 每隔500ms创建一个子弹
setInterval(function(){
biuBiuBiu();
},500)
// 让子弹飞
function bulletFly(){
setInterval(function(){
// 取得所有的子弹
var bullets = document.querySelectorAll(‘.bullet‘)
var currentTop;
for(var i = 0; i<bullets.length;i++){
currentTop = bullets[i].offsetTop;
if(currentTop < -100){
bullets[i].remove()
}else{
bullets[i].style.top = currentTop -5+ ‘px‘
}
}
},16)
}
bulletFly()
</script>
</body>
</html>
飞机图片:

原文:https://www.cnblogs.com/rabbit-lin0903/p/11620783.html