天天看点

javascript猜数字游戏,随机数猜数字实现界面一、代码总结

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

实现界面

javascript猜数字游戏,随机数猜数字实现界面一、代码总结

一、代码

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;
}
           

图片
javascript猜数字游戏,随机数猜数字实现界面一、代码总结

javascript猜数字游戏,随机数猜数字实现界面一、代码总结
javascript猜数字游戏,随机数猜数字实现界面一、代码总结
javascript猜数字游戏,随机数猜数字实现界面一、代码总结
javascript猜数字游戏,随机数猜数字实现界面一、代码总结
javascript猜数字游戏,随机数猜数字实现界面一、代码总结

总结

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

继续阅读