猜数游戏的HTML代码
时间: 2023-07-09 08:08:26 浏览: 92
猜数游戏代码
以下是一个猜数游戏的HTML代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>猜数游戏</title>
<meta charset="UTF-8">
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
text-align: center;
}
form {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 20px;
}
input[type="number"] {
padding: 10px;
margin-bottom: 10px;
width: 100%;
max-width: 300px;
border: none;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0,0,0,0.3);
box-sizing: border-box;
font-size: 1.2em;
text-align: center;
}
input[type="submit"] {
padding: 10px;
width: 100%;
max-width: 300px;
border: none;
border-radius: 5px;
background-color: #4CAF50;
color: white;
font-size: 1.2em;
cursor: pointer;
}
.result {
margin-top: 20px;
font-size: 1.2em;
text-align: center;
}
.result.correct {
color: green;
}
.result.incorrect {
color: red;
}
</style>
</head>
<body>
<h1>猜数游戏</h1>
<form>
<label for="guess">猜一个1到100之间的整数:</label>
<input type="number" id="guess" name="guess" min="1" max="100" required>
<input type="submit" value="猜">
</form>
<div class="result" id="result"></div>
<script>
var answer = Math.floor(Math.random() * 100) + 1;
var resultDiv = document.getElementById("result");
var form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault();
var guess = parseInt(document.getElementById("guess").value);
if (guess === answer) {
resultDiv.textContent = "恭喜你,猜对了!";
resultDiv.classList.remove("incorrect");
resultDiv.classList.add("correct");
} else if (guess < answer) {
resultDiv.textContent = "猜的数字太小了,请再试一次。";
resultDiv.classList.remove("correct");
resultDiv.classList.add("incorrect");
} else {
resultDiv.textContent = "猜的数字太大了,请再试一次。";
resultDiv.classList.remove("correct");
resultDiv.classList.add("incorrect");
}
});
</script>
</body>
</html>
```
这个代码会生成一个简单的猜数游戏界面,其中包括一个输入框和一个提交按钮,用于让用户输入猜测的数字,以及一个结果区域,用于显示猜测结果。当用户提交猜测后,JavaScript代码会比较用户猜测的数字与正确答案,并显示相应的结果。
阅读全文