HTML+CSS+JS实现猜数字游戏
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>猜数字游戏</title>
<link rel="stylesheet" href="index.css">
<script src="index.js" defer></script>
</head>
<body>
<h1>猜数字游戏</h1>
<p>请输入一个1-100之间的数字:</p>
<input type="number" id="userGuess" min="1" max="100">
<br>
<button onclick="checkGuess()">提交</button>
<p id="userResult"></p>
<p id="count"></p>
<ul id="history"></ul>
<button onclick="refresh()">再来一次</button>
</body>
</html>
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;
}
运行结果