效果圖如下:

打字游戲
html結(jié)構(gòu)代碼:
<style>
.box{
width: 600px;
height: 400px;
background-color: hotpink;
position: relative;
}
</style>
<button class="start">開始</button>
得分:<span class="scoreBox">0</span>分
<div class="box"></div>
js邏輯代碼:
// 獲取所有標(biāo)簽
var startBtn = document.querySelector('.start');
var scoreBox = document.querySelector('.scoreBox');
var box = document.querySelector('.box');
// 定義大定時(shí)器變量
var timerId;
// 點(diǎn)擊開始按鈕,開始游戲
startBtn.addEventListener('click', click);
function click() {
// 分?jǐn)?shù)從0開始計(jì)算
scoreBox.innerText = 0;
// 間隔很短的時(shí)間,從上向下下來一個(gè)文字,這個(gè)文件不停的向下移動(dòng)
timerId = setInterval(function() {
// 創(chuàng)建一個(gè)b標(biāo)簽
var b = document.createElement('b');
// 給b標(biāo)簽中放入隨機(jī)小寫字母 - 小寫字母的阿斯克碼是 97~122
var code = getRandom(97, 123);
// 將隨機(jī)的阿斯克碼轉(zhuǎn)成小寫字母
var word = String.fromCharCode(code);
// 將小寫字符放入b標(biāo)簽中
b.innerText = word;
// 定義b標(biāo)簽的top值
var t = 0;
// 設(shè)置b標(biāo)簽樣式
setStyle(b, {
width: '30px',
height: '30px',
backgroundColor: '#00f',
color: '#fff',
borderRadius: '50%',
textAlign: 'center',
lineHeight: '30px',
position: 'absolute',
top: t,
left: getRandom(0, box.clientWidth - 30 + 1) + 'px'
})
// 將b標(biāo)簽放入box盒子中
box.appendChild(b)
// 讓b標(biāo)簽向下移動(dòng)
// 將每個(gè)小定時(shí)器放在被移動(dòng)的b標(biāo)簽屬性中
b.timer = setInterval(function() {
// 讓top值變量t,每隔20毫秒增加2px
t += 2;
// 限制top值
if(t > box.clientHeight - 30) {
t = box.clientHeight - 30;
// 將大定時(shí)器停止,將所有小定時(shí)器停止,彈出游戲結(jié)束
clearInterval(timerId);
alert('游戲結(jié)束')
// 遍歷所有b標(biāo)簽,停止每個(gè)b標(biāo)簽上的定時(shí)器 - 并刪除所有b標(biāo)簽
for(var i = box.children.length - 1; i >= 0; i--) {
clearInterval(box.children[i].timer);
box.removeChild(box.children[i])
}
}
// 將增加后的t設(shè)置到b標(biāo)簽的top
b.style.top = t + 'px';
}, 20)
}, 1000)
}
// 鼠標(biāo)抬起時(shí),判斷按下的鍵,是否在所有b標(biāo)簽內(nèi)容中的1個(gè),是的話就得分1,停止這個(gè)b標(biāo)簽的定時(shí)器,刪除這個(gè)b標(biāo)簽
document.addEventListener('keyup', keyup);
function keyup() {
// 獲取事件對(duì)象
var e = window.event;
// 獲取鍵盤碼
var keycode = e.keyCode || e.which;
// 將鍵盤碼轉(zhuǎn)成小寫字母
var word = String.fromCharCode(keycode).toLowerCase();
// 判斷這個(gè)字母是否是b標(biāo)簽內(nèi)容中的一個(gè)
for(var i = 0; i < box.children.length; i++) {
if(word === box.children[i].innerText) {
// 得分加1
var score = +scoreBox.innerText + 1;
// 將分?jǐn)?shù)放進(jìn)得分盒子中
scoreBox.innerText = score;
// 停止這個(gè)b標(biāo)簽的定時(shí)器
clearInterval(box.children[i].timer);
// 刪除這個(gè)b標(biāo)簽
box.removeChild(box.children[i]);
break;
}
}
}
// 獲取隨機(jī)數(shù)的函數(shù)
function getRandom(a, b = 0) {
var max = a;
var min = b;
if(a < b) {
max = b;
min = a;
}
return Math.floor(Math.random() * (max - min)) + min;
}
// 批量設(shè)置樣式的函數(shù)
function setStyle(ele, styleObj) {
for(var attr in styleObj) {
ele.style[attr] = styleObj[attr];
}
}