javascript猜数字游戏,随机数猜数字

思路:获取输入框中输入的值使用随机函数 var input1=document.getElementById(“shuru”).value;使用随机函数random获取随机数,将这两个数使用if语句进行对比,consol.log后台打印猜数的结果

实现界面

在这里插入图片描述

一、代码

html代码


<!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>
    <link rel="stylesheet" href="caijiang.css">
    <style>
      
    </style>
</head>
<body>
    <div class="all">
        <div><img id="img1" src="bg.jpg" alt=""></div>
        <div class="left">
            <input type="text" id="shuru" name="shuru">
            <input type="button" id="btn">
        </div>
        <div class="right">
            
        </div>
    </div>
    
    <script>
        
        var btn1=document.getElementById("btn");
        var n=Math.round(Math.random()*10);
        btn1.onclick=function(){
            
            var input1=document.getElementById("shuru").value;
            //判断随机数是否符合input中的值
            //获取随机数
            //random获取的随机数为0~1的小数,需要进行转化 
            //round四舍五入
                       
            console.log(n);
            console.log(input1);
            if(input1> n){
                console.log("你猜大了哦!!");
            }else if(input1== n){
                console.log("你猜对了哦!!");
                
            }else{
                console.log("你猜小了哦!!");
            }
        }
    </script>
</body>
</html>

css代码

body{
    position: relative;
}
#img1{position: absolute;top:0;left:0;
width: 100%;height:auto;z-index: -100;

}
.left{position: relative;top:200px;left:8%;
    width: 600px;height: 456px;background: url("main.png");
    background-size:cover;
}
.left #shuru{font-size: 25px;color:#000;padding-left:20px;
    position: absolute;top: 239px;left: 118px;
    width: 353px;height: 50px;border:1px solid green;outline: none;border-radius: 5px;
}
.left #btn{
    position: absolute;top: 319px;left: 261px;

    width: 82px;height: 82px;border-radius: 50%;
    background: url("button.png");background-size:82px 82px ; outline: none;
}
.right{position: absolute;top: 319px;right: 28%;
    width: 200px;height: 230px;background: url("win.png");background-size: 200px auto;
}

图片在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

总结

使用随即函数random获取随机数,获取到的随机数为0-1的小数,所以乘以10,得到1-10的随机数,Math.round将小数四舍五入取整,取整也可以使用parseInt

 var n=Math.round(Math.random()*10);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值