HTML+CSS+JS实现猜数字游戏
index.html
猜数字游戏 猜数字游戏
请输入一个1-100之间的数字:
index.js
const randomNumber = Math.floor(Math.random() * 100) + 1; let count = 0; const history = document.getElementById('history'); function checkGuess() { const userGuess = parseInt(document.getElementById('userGuess').value); if (isNaN(userGuess) || userGuess < 1 || userGuess > 100) { document.getElementById('userResult').textContent = '请输入一个有效的数字(1-100)'; return; } count++; let message = ''; if (userGuess === randomNumber) { message = `恭喜您,猜对啦,一共用了${count}次`; document.getElementById('userGuess').disabled = true; document.querySelector('button').disabled = true; } else if (userGuess < randomNumber) { message = `对不起,您猜小了,请继续猜测`; } else { message = `对不起,您猜大了,请继续猜测`; } document.getElementById('userResult').textContent = message; document.getElementById('count').textContent = `猜测次数${count}`; const li = document.createElement('li'); li.textContent = `第${count}次猜测:${userGuess} ${message}`; history.appendChild(li); document.getElementById('userGuess').value = ''; } function refresh(){ location.reload() }
index.css
*{ margin: 0; padding: 0; box-sizing: border-box; } body{ background: rgb(212, 250, 250); text-align: center; } h1{ margin: 10px; padding: 10px; } p{ margin: 10px; font-size: 20px; } input{ margin: 10px; width: 120px; height: 40px; border: 1px solid #ccc; border-radius: 20%; font-size: 20px; } button{ background-color: rgb(139, 196, 237); color: white; width: 80px; border-radius: 8px; height: 40px; cursor: pointer; font-size: 18px; margin: 20px; } button:hover{ background-color: rgb(56, 130, 233); } ul{ margin: 6px; } #userResult{ color: rgb(246, 12, 12); } #history{ margin-top: 20px; }
还没有评论,来说两句吧...