我遵循了有关如何使用 JS/HTML 构建基本游戏的教程,现在我正在扩展它。 Game here
- 按空格开火
- 按右箭头向右转,按左箭头向左转
我能够获取敌人与导弹之间碰撞的位置,并使用 innerHTML
将新的 #explosion
添加到 html。我很困惑如何在 1 秒后消除爆炸。
const explosion = (topEn, leftEn) => {
document.getElementById('explosions').innerHTML +=
`
<div id="explosion" style='
left:${leftEn}px;
top: ${topEn}px;
'></div>
`;
}
#explosion{
background-image: url("assets/explosion.png");
height: 50px;
width: 50px;
position: absolute;
}
最佳答案
如果没有你的其余代码,很难给你一个准确的展示,但这主要是我的评论所指的。
const explosion = (topEn, leftEn, delay = 1000) => {
const div = document.createElement('div');
div.id = 'explosion';
div.style.top = topEn + 'px';
div.style.left = leftEn + 'px';
document.getElementById('explosions').append(div);
setTimeout(() => {
div.remove()
}, delay);
}
explosion(200, 200, 1000);
setTimeout(()=> explosion(300, 400, 800), 500)
#explosion {
background-image: url("assets/explosion.png");
height: 50px;
width: 50px;
position: absolute;
/* I added this to be able to see the divs*/
background-color: red;
}
body, html, #explosions {
height: 100%;
width: 100%;
}
<div id="explosions"></div>
注意事项:
如果您可能同时在 DOM 中有多个相同类型的元素(即)爆炸,您应该转而使用类而不是 ID。 ID 是唯一 标识符,因此虽然您可以拥有多个具有相同 ID 的元素,但这会导致您出现意想不到的结果。如果您的游戏能够在任何给定时间发生超过 1 次爆炸,请将 #explosion
移动到 .explosion
关于JavaScript innerHTML 几秒钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59230723/