Simple HTML Guessing Game - Code & Tutorial
<html>
<head>
<title>Guess the Number</title>
<style type="text/css">
#guessForm {
background-color: #bbb;
padding: 5px 10px;
font-family: sans-serif;
font-weight: bold;
}
<pre><code> #guessForm input {
font-size: 1.2em;
padding: 4px;
}
#guessForm button {
font-size: 1.2em;
padding: 6px;
background-color: #ccc;
border: 0;
}
#result {
font-family: sans-serif;
font-size: 1.2em;
font-weight: bold;
padding: 10px;
}
</style>
</code></pre>
</head>
<body>
<div id="container">
<h1>Guess the Number</h1>
<p>I'm thinking of a number between 1 and 10. Can you guess it?</p>
<pre><code> <form id="guessForm">
<input type="text" name="guess" />
<button type="submit">Guess</button>
</form>
<div id="result"></div>
</div>
<script>
const randomNumber = Math.floor(Math.random() * 10) + 1;
const guessForm = document.getElementById('guessForm');
const result = document.getElementById('result');
guessForm.addEventListener('submit', e => {
e.preventDefault();
const guess = parseInt(guessForm.guess.value);
if (guess === randomNumber) {
result.textContent = 'You guessed it!';
} else {
result.textContent = 'Wrong! The number was ' + randomNumber;
}
});
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmdf 著作权归作者所有。请勿转载和采集!