案例-猜数字游戏
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>猜数字游戏</title>
<style>
.false{
color: red;
}
.true{
color: green;
}
</style>
</head>
<body>
<div>
<input class="but" type="button" value="重新开始一局游戏" onclick="restart()">
</div>
<div>
请输入要猜的数字:<input class="num" type="text" value="">
<input class="guess" type="button" value="猜">
</div>
<div>
以及猜的次数:<span class="already">0</span>
</div>
<!-- <div>结果:<span class="result">测试结果</span></div> -->
<div>结果:<span class="result"></span></div>
</body>
<script>
let but = document.querySelector('.but')
let num = document.querySelector('.num')
let guess = document.querySelector('.guess')
let already = document.querySelector('.already')
let result = document.querySelector('.result')
// ---------------------------------------------------------------------------------------
// 控制台显示
console.dir(but)
console.dir(num)
console.dir(guess)
console.dir(already)
console.dir(result)
// ---------------------------------------------------------------------------------------
// 随机生成1~100数字
let guessNumber = Math.floor(Math.random() * 100) + 1
console.log('随机数字是:'+guessNumber)
// ---------------------------------------------------------------------------------------
function restart(){
num.value = 0
already.textContent = 0
result.innerHTML = ""
guessNumber = Math.floor(Math.random() * 100) + 1
console.log('随机数字是:'+guessNumber)
}
guess.onclick = function(){
let numValue = parseInt(num.value)
if(numValue > guessNumber){
result.innerHTML = "猜大了"
result.className = false;
}
else if (numValue < guessNumber) {
result.innerHTML = "猜小了"
result.className = 'false';
} else {
result.innerHTML = "恭喜!猜对了~"
result.className = 'true';
}
already.textContent = parseInt(already.textContent) + 1
}
</script>
</html>