案例-猜数字游戏

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>猜数字游戏</title> <style> .false{ color: red; } .true{ color: green; } </style> </head> <body> <div> <input class="but" type="button" value="重新开始一局游戏" onclick="restart()"> </div> <div> 请输入要猜的数字:<input class="num" type="text" value=""> <input class="guess" type="button" value=""> </div> <div> 以及猜的次数:<span class="already">0</span> </div> <!-- <div>结果:<span class="result">测试结果</span></div> --> <div>结果:<span class="result"></span></div> </body> <script> let but = document.querySelector('.but') let num = document.querySelector('.num') let guess = document.querySelector('.guess') let already = document.querySelector('.already') let result = document.querySelector('.result') // --------------------------------------------------------------------------------------- // 控制台显示 console.dir(but) console.dir(num) console.dir(guess) console.dir(already) console.dir(result) // --------------------------------------------------------------------------------------- // 随机生成1~100数字 let guessNumber = Math.floor(Math.random() * 100) + 1 console.log('随机数字是:'+guessNumber) // --------------------------------------------------------------------------------------- function restart(){ num.value = 0 already.textContent = 0 result.innerHTML = "" guessNumber = Math.floor(Math.random() * 100) + 1 console.log('随机数字是:'+guessNumber) } guess.onclick = function(){ let numValue = parseInt(num.value) if(numValue > guessNumber){ result.innerHTML = "猜大了" result.className = false; } else if (numValue < guessNumber) { result.innerHTML = "猜小了" result.className = 'false'; } else { result.innerHTML = "恭喜!猜对了~" result.className = 'true'; } already.textContent = parseInt(already.textContent) + 1 } </script> </html>
上一篇:使用前端三剑客实现一个备忘录


下一篇:常用组件详解(九):学习率更新策略-5.PloyLR