最近手痒,把一个有三种难度的练习打字得分的小游戏做了出来…css可以自己添加。
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>.gameOvers {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);width: 400px;height: 400px;background-color: skyblue;color: red;display: none;}.testClassList {display: block;color: rgb(6, 6, 6);}.hide {display: none;}</style>
</head><body><div class="testClassList">测试classList</div><input type="text" placeholder="搜索城市" class="input"><button class="button" type="button" onclick="let tips = alert('你点击了搜索按钮!');">搜索</button><div class="word"></div><div class="scores">0</div><div class="times"></div><div class="gameOvers"></div><div><select class="select"><option value="jiandan">简单</option><option value = "zhongdeng" selected>中等</option><option value="jiaonan">较难</option></select></div><script>let select = document.querySelector('.select');let word = document.querySelector('.word');let scores = document.querySelector('.scores');let inputs = document.querySelector('.input');let times = document.querySelector('.times');let games = document.querySelector('.gameOvers');let test = document.querySelector('.testClassList');let randows = ['张三', '李四', '王五', '小强', '小李'];// 难度选择let difficulty = localStorage.getItem('selects') !== null ? localStorage.getItem('selects') : 'zhongdeng'// 更新难度选择difficulty.value = localStorage.getItem('selects') !== null ? localStorage.getItem('selects') : 'zhongdeng'// 下拉框事件监听select.addEventListener('change', e => {difficulty = e.target.value;localStorage.setItem('selects', difficulty)})scores.addEventListener('click', () => {// 如果存在就删除,没有就添加test.classList.toggle('hide')})// 聚焦inputs.focus()// 取到randows数组里面的数据function randowData() {return randows[Math.floor(Math.random() * randows.length)]}// 开始倒数const timeInterval = setInterval(updateTime, 1000);let time = 10;function updateTime() {time--;times.innerHTML = time + 's';if (time <= 0) {clearInterval(timeInterval)gameOver()}};// 游戏结束function gameOver() {games.innerHTML = `<h1>游戏结束</h1><p>最终得分${score}</p><button onclick="location.reload()">再玩一次</button>`;games.style.display = 'block'}// 把生成的内容插入到dom中function addWord() {// 把randomWord公布出去randomWord = randowData()word.innerHTML = randomWord}// 更新得分let score = 0;function updateScore() {score++;scores.innerHTML = score}addWord()inputs.addEventListener('input', (e) => {if (e.target.value === randomWord) {// 更换随机生成的数据addWord()// 更新得分updateScore()inputs.value = "";if (difficulty === 'jiaonan') {time += 5;} else if (difficulty === 'zhongdeng') {time += 10} else {time += 15;}// 并且更新一下时间updateTime()}})</script>
</body></html>