实现一个网页版的简易猜数字游戏
效果
代码截图
相关代码
< ! DOCTYPE html>
< html lang= "en" >
< head>
< meta charset= "UTF-8" >
< meta name= "viewport" content= "width=device-width, initial-scale=1.0" >
< title> Document< / title>
< style>
. false {
color : red;
}
. true {
color : green;
}
< / style>
< / head>
< body>
< input class = "reset_button" type= "button" value= "重写开始一局游戏" onclick= "reSet()" > < br>
请输入的数字:< input class = "to_guess_num" type= "text" > < input type= "button" value= "猜" onclick= "Guess()" > < br>
已经猜的次数:< span class = "has_guess_num" > 0 < / span> < br>
结果 : < span class = "result" > < / span>
< / body>
< script>
let to_guess_num_element = document. querySelector ( '.to_guess_num' )
let input_num_element = document. querySelector ( '.has_guess_num' )
let result_element = document. querySelector ( '.result' )
function reSet ( ) {
to_guess_num_element. value = ""
input_num_element. innerHTML = 0
result_element. innerHTML = ""
}
let num = Math. floor ( Math. random ( ) * 100 ) + 1
console. log ( num)
function Guess ( ) {
input_num_element. innerHTML = parseInt ( input_num_element. innerHTML) + 1
if ( num < parseInt ( to_guess_num_element. value) ) {
result_element. innerHTML = "猜大了"
result_element. className = 'false'
} else if ( num > parseInt ( to_guess_num_element. value) ) {
result_element. innerHTML = "猜小了"
result_element. className = 'false'
} else {
result_element. innerHTML = "猜中了"
result_element. className = 'true'
}
to_guess_num_element. value = ""
}
< / script>
< / html>