天天看點

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

繼續閱讀