<!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>飞机</title>
</head>
<style>
img {
position: absolute;
}
#fly {
left: 100px;
top: 200px;
}
</style>
<body>
<img src="./images/2.png" style="display: none;" id="pos0">
<img src="./images/2.png" style="display: none;" id="pos1">
<img src="./images/2.png" style="display: none;" id="pos2">
<img src="./images/2.png" style="display: none;" id="pos3">
<img src="./images/2.png" style="display: none;" id="pos4">
<img src="./images/1.gif" id="fly">
</body>
<script>
var fly = document.getElementById("fly");
document.onkeydown = function(e) {
var e = e || window.event;
console.log(e.keyCode);
switch (e.keyCode) {
case 37:
{
fly.style.left = fly.offsetLeft - 10 + "px";
break;
}
case 38:
{
fly.style.top = fly.offsetTop - 10 + "px";
break;
}
case 39:
{
fly.style.left = fly.offsetLeft + 10 + "px";
break;
}
case 40:
{
fly.style.top = fly.offsetTop + 10 + "px";
break;
}
case 32:
{
for (var i = 0; i < 5; i++) {
var img = document.getElementById("pos" + i);
if (img.style.display == "none") {
img.style.display = "block";
console.log(fly.offsetLeft + fly.offsetWidth / 2);
img.style.left = fly.offsetLeft + fly.offsetWidth / 2 + "px";
img.style.top = fly.offsetTop + "px";
break;
}
}
}
}
}
setInterval(function() {
for (var i = 0; i < 5; i++) {
var pos = document.getElementById("pos" + i);
pos.style.top = pos.offsetTop - 10 + "px";
if (pos.offsetTop < -7) {
pos.style.display = "none"
}
}
}, 50)
</script>
</html>
来源:CSDN
作者:慢慢学编程
链接:https://blog.csdn.net/weixin_40492102/article/details/104134768