需求分析:
1:随机产生数字;
2:根据输入的数字判断大小
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 157px;
height: 50px;
border: 2px solid gray;
margin-top: 10px;
}
#check{
width: 157px;
height: 50px;
border: 2px solid gray;
margin-top: 10px;
}
.box{
margin: 10px auto;
width: 200px;
height: auto;
}
</style>
<div class="box">
<form id="form">
<label>
<input type="text" placeholder="请输入你猜的数字">
</label>
</form>
<div id="box"></div>
<button style="margin-top: 10px;" id="butt">查看正确答案</button>
<div id="check"></div>
<button id="newGame">再猜一次</button>
</div>
<script>
// 生出随机数0-100
var number = Math.floor(Math.random()*100);
// console.log(number)
var inputs = document.getElementById("inputs")
var form = document.getElementById("form");
var box = document.getElementById("box");
var butt = document.getElementById("butt");
var check = document.getElementById("check")
var newGame = document.getElementById("newGame");
var hidd = 1;
// 聚焦事件
form.elements[0].addEventListener("focus",function(){
this.placeholder=" ";
})
// 这里是失焦事件
form.elements[0].addEventListener("blur",function(){
this.placeholder="请输入你猜的数字";
if(this.value==number){
box.innerHTML="你猜对了"
}else if(this.value>number&&this.value<=100){
box.innerHTML="你猜大了"
}else if(this.value<number&&this.value>=0){
box.innerHTML="你猜小了"
}else{
box.innerHTML="请输入0-100的数字"
}
})
// 点击时间实现按钮的切换
butt.onclick=function(){
if(hidd==1){
butt.innerHTML="点击隐藏"
check.innerHTML=number
hidd=0
}else if(hidd==0){
butt.innerHTML="查看正确答案"
check.innerHTML=""
hidd=1
}
}
// 点击事件
newGame.onclick=function(){
number = Math.floor(Math.random()*100);
check.innerHTML="";
hidd=1;
butt.innerHTML="查看正确答案"
box.innerHTML=""
form.elements[0].value=""
}
</script>
</body>
</html>
小总结:要获取input框里面输入的值,可以通过表单里面聚焦、失焦事件实现;生成的随机数与输入的数字判断时条件要写严密,js小萌新一枚,希望和大家共同分享交流,一起学习