La méthode du temporisateur imbriqué est utilisée ici
js:
window.addEventListener('load', () => {
// 获取元素
let start = document.querySelector('.start') // 开始按钮
let mole = document.querySelectorAll('.mole') // 打鼹鼠
let score = document.querySelector('.score') // 数字文本
let timerId // 定时句柄
let index // 随机数索引
let num = 0 // 击打次数
// 开始添加点击事件
start.addEventListener('click', () => {
// 重新点击开始,击打次数清零
num = 0
score.innerHTML = num
start.style.display = 'none' // 隐藏开始按钮,以防多次点击出现定时器bug
timerId = setInterval(() => { // 添加打地鼠定时器
// 生成随机数
index = parseInt(Math.random() * mole.length)
mole[index].style.top = '0%' // 设置地鼠样式从下往上出来
time = setTimeout(() => { // 添加定时器嵌套延时器,延时器只执行一遍
mole[index].style.top = '70%' // 设置地鼠样式钻回地底
}, 500)
}, 1000)
// 添加倒计时10秒后停止打地鼠定时器
setInterval(() => {
start.style.display = 'block'
clearInterval(timerId)
}, 10000)
})
// 点击敲打鼹鼠
mole.forEach((value, index) => {
value.addEventListener('click', () => {
mole[index].style.top = '70%'
num++
score.innerHTML = num
})
});
html:
<h1>Whack-a-mole! <span class="score">0</span></h1>
<p><button class="start">Start</button></p>
<div class="game">
<div class="hole hole1">
<div class="mole"></div>
</div>
<div class="hole hole2">
<div class="mole"></div>
</div>
<div class="hole hole3">
<div class="mole"></div>
</div>
<div class="hole hole4">
<div class="mole"></div>
</div>
<div class="hole hole5">
<div class="mole"></div>
</div>
<div class="hole hole6">
<div class="mole"></div>
</div>
</div>
<h2 class="game-status"></h2>
<script src="./index.js"></script>
CSS:
html {
box-sizing: border-box;
font-size: 10px;
background: #ffc600;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
padding: 0;
margin: 0;
font-family: 'Amatic SC', cursive;
}
h1,
h2 {
text-align: center;
font-size: 10rem;
line-height: 1;
margin-bottom: 0;
}
h2 {
font-size: 8rem;
}
.score {
background: rgba(255, 255, 255, 0.2);
padding: 0 3rem;
line-height: 1;
border-radius: 1rem;
}
p {
height: 5rem;
text-align: center;
}
button {
margin: 0 auto;
width: 10rem;
font-size: 3rem;
font-family: 'Amatic SC', cursive;
-webkit-appearance: none;
appearance: none;
font-weight: bold;
background: rgba(255, 255, 255, 0.2);
border: 1px solid black;
border-radius: 1rem;
}
.game {
width: 600px;
height: 400px;
display: flex;
flex-wrap: wrap;
margin: 0 auto;
}
.hole {
flex: 1 0 33.33%;
overflow: hidden;
position: relative;
}
.hole:after {
display: block;
background: url(dirt.svg) bottom center no-repeat;
background-size: contain;
content: '';
width: 100%;
height: 70px;
position: absolute;
z-index: 2;
bottom: -30px;
}
.mole {
background: url('mole.svg') bottom center no-repeat;
background-size: 60%;
position: absolute;
top: 70%;
width: 100%;
height: 100%;
transition: all 0.4s;
}
.hole.up .mole {
top: 0;
}