标签:知识 按钮 dom sans 随机数 body document UNC floor
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>猜数字游戏</title>
<style>
html {
font-family: sans-serif
}
body {
width: 50%;
max-width: 800px;
min-width: 480px;
margin: 0 auto
}
.lastResult {
color: white;
padding: 3px
}
</style>
</head>
<body>
<h1>猜数字游戏</h1>
<p>我刚才随机选定了一个100以内的自然数。看你能否在 10 次以内猜中它。每次我都会告诉你所猜的结果是高了还是低了。</p>
<div class="form">
<label for="guessField">请猜数: </label>
<input type="text" id="guessField" class="guessField">
<input type="submit" value="确定" class="guessSubmit">
</div>
<div class="resultParas">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
<script>
var randomNumber =Math.floor(Math.random()*100)+1;
var guesses = document.querySelector('.guesses');
var lastResult= document.querySelector('.lastResult');
var lowOrHi= document.querySelector('.lowOrHi');
var guessSubmit = document.querySelector('.guessSubmit');
var guessField = document.querySelector('.guessField');
var guessCount = 1;
var resetButton;
guessField.focus();
guessSubmit.addEventListener('click', checkGuess);
function checkGuess(){
//获取输入框的值
var userGuess = Number(guessField.value);
if (guessCount === 1) {
guesses.textContent = '上次猜的数:';
}
guesses.textContent += userGuess + ' ';
if(userGuess === randomNumber){
lastResult.textContent ='恭喜你!猜对了';
lastResult.style.backgroundColor ='green';
lowOrHi.textContent = '';
} else if(guessCount === 10){
lastResult.textContent = '!!! GAME OVER !!! ';
setGameOver();
}
else{
lastResult.textContent ='你猜错了!';
lastResult.style.backgroundColor ='red';
if(userGuess<randomNumber){
lowOrHi.textContent ='你猜低了!'
}else if(userGuess>randomNumber){
lowOrHi.textContent ='你猜高了';
}
}
guessCount++;
guessField.value='';
guessField.focus();
}
function setGameOver(){//游戏结束
//禁止输入和提交
guessField.disabled =true;
guessSubmit.disabled =true;
// 添加开始新游戏按钮 在html的底部
resetButton = document.createElement('button');
resetButton.textContent ='开始新游戏';
document.body.appendChild(resetButton);
// 在开始新游戏 设置了一个事件监听器 resetGame()
resetButton.addEventListener('click',resetGame);
}
function resetGame(){//重新开始游戏
//重置数据
guessCount =1;
//将 class='resultParas' 下面的p元素的内容清空
var resetParas = document.querySelectorAll('.resultParas p');
for (var i = 0;i<resetParas.length;i++){
resetParas[i].textContent = '';
}
//移除 resetButton按钮
resetButton.parentNode.removeChild(resetButton);
//启用表单元素,清空文本域并聚焦于此,准备接受新猜测的数字。
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
//删除lastResult段落的背景颜色。
lastResult.style.backgroundColor = 'white';
//生成一个新的随机数!
randomNumber = Math.floor(Math.random() * 100) + 1;
}
</script>
</body>
</html>
本文学习案列来自:MDN web docs
标签:知识 按钮 dom sans 随机数 body document UNC floor
原文地址:https://www.cnblogs.com/wentutu/p/10275766.html