首先视图层布局如下:
<body>
<div class="box">
<div class="msg">按回车键 开始/暂停</div>
<div class="time"></div>
</div>
</body>
其次对视图层添加样式:
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 800px;
height: 100vh;
background-color: black;
margin: 0 auto;
position: relative;
overflow: hidden;
}
.zm {
width: 30px;
height: 30px;
text-align: center;
line-height: 30px;
font-size: 20px;
background-color: lightblue;
position: absolute;
transition: all 0.5s;
color: white;
}
.msg {
width: 60%;
height: 200px;
background-color: rgba(255, 0, 0, 0.201);
text-align: center;
line-height: 200px;
color: white;
font-size: 40px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
.time {
width: 100%;
color: red;
text-align: center;
position: absolute;
left: 0;
top: 0;
}
</style>
最后是利用JavaScript把需要实现的功能渲染到div盒子里
<script>
//封装了返回随机颜色的方法
function getColor() {
let color = '#'
let colorNums = '0123456789abcdef'
for (let i = 0; i < 6; i++) {
color += colorNums[Math.floor(Math.random() * 16)]
}
return color
}
//随机返回一个字母的方法
function getZm() {
let zmList = 'ABCDEFGHIGKLMNOPQRSTUVWXYZ'
return zmList[Math.floor(Math.random() * 26)]
}
let timer1 = null
let timer2 = null
function creatZm() {
//获取大容器
let box = document.querySelector('.box')
timer1 = setInterval(() => {
let timestart = performance.now()
let time1 = document.querySelector('.time')
time1.innerHTML = '你已经坚持了' + Math.floor(timestart / 1000) + "秒";
//使用定时器生成字母div
let zm = document.createElement('div')
zm.className = 'zm'
zm.innerText = getZm()
zm.style.left = Math.random() * 770 + 'px'
zm.style.top = '-15px'
zm.style.backgroundColor = getColor()
box.appendChild(zm)
}, 300);
}
function downZm() {
//使用定时器控制所有字母div下落
//offsetTop属性获取当前元素到父元素的上边距
//offsetLeft属性获取当前元素到父元素的左边距
timer2 = setInterval(() => {
//获取生成的字母div
let zm = document.querySelectorAll('.zm')
zm.forEach(z => {
//如果字母走出去了,游戏就结束了
if (z.offsetTop >= window.innerHeight) {
//清除定时器
clearInterval(timer2)
clearInterval(timer1)
timer1 = null
timer2 = null
document.querySelector('.msg').style.display = 'block'
document.querySelector('.msg').innerText = 'GAME OVER'
}
z.style.top = z.offsetTop + 60 + 'px'
})
}, 100);
}
//按下对应按键消除字母div
window.onkeyup = function (e) {
//获取所有字母
let zm = document.querySelectorAll('.zm')
if (e.key == 'Enter') {
if (timer1 == null) {
if (document.querySelector('.msg').innerText == 'GAME OVER') {
document.querySelector('.msg').innerText = '按回车键 开始/暂停'
document.querySelectorAll('.zm').forEach(r => {
r.remove()
})
} else {
creatZm()
downZm()
document.querySelector('.msg').style.display = 'none'
}
} else {
//清除定时器
clearInterval(timer2)
clearInterval(timer1)
timer1 = null
timer2 = null
document.querySelector('.msg').style.display = 'block'
}
}
zm.forEach(z => {
console.log(z);
if (z.innerText.toUpperCase() == e.key.toUpperCase()) {
z.remove()
}
})
}
</script>