Simple HTML Guessing Game: Learn to Code with This Fun Project
<html>
<head>
<title>Guess the Number</title>
<style>
body {
background-color: skyblue;
}
#container {
margin: 0 auto;
width: 400px;
padding: 10px;
border: 3px solid black;
}
#input {
padding: 4px 10px;
margin: 4px 0;
}
#submit {
padding: 4px 10px;
}
#result {
padding: 4px 10px;
}
</style>
</head>
<body>
<div id='container'>
<h1>Guess the Number!</h1>
<p>Guess a number between 1 and 10.</p>
<form action="">
<input type='number' id='input' min='1' max='10'>
<input type='submit' id='submit' value='Guess'>
</form>
<div id='result'></div>
</div>
<script>
let randomNumber = Math.floor(Math.random() * 10) + 1;
let guess;
let form = document.querySelector('form');
let result = document.getElementById('result');
form.addEventListener('submit', function(e) {
e.preventDefault();
guess = document.getElementById('input').value;
if(parseInt(guess) === randomNumber) {
result.innerHTML = 'Congratulations! You guessed the number!';
} else {
result.innerHTML = 'Sorry, that is not correct. Try again.';
}
});
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmnm 著作权归作者所有。请勿转载和采集!