js隨機點名器(簡單)


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>

    <style>

    .box {

        width: 200px;

        height: 200px;

        line-height: 200px;

        background-color: #ccc;

        font-size: 30px;

        text-align: center;

    }

    </style>

</head>

<body>

    <div class="box">此乃點名器</div>

    <input type="button" value="點名" id="btn">

    <!-- <button id="btn">點名</button> -->

    <script>

        var btn = document.getElementById("btn");

        var box = document.getElementsByClassName("box")[0];

// 3、寫一個隨機抽名的案例?(點擊按鈕開啟定時器,

// 定時器中去隨機抽取人名,把全班的人放在一個數組中,只要想辦法獲取隨機的索引號就可以)

        btn.onclick = function() {

            if(this.value==="點名") {

            function fn() {

            var arr = ["張三","李四","王五","趙六","黑七","白八","紫九","紅薯"];

            var index = parseInt(Math.random()*arr.length);

         var n1 = parseInt(Math.random()*255+1);

         var n2 = parseInt(Math.random()*255+1);

         var n3 = parseInt(Math.random()*255+1);

            box.style.background ="rgb("+n1+","+n2+","+n3+")" ;

            box.innerHTML = arr[index]; 

            } 

            this.value = "停止";

            //定時器不加var聲明,涉及到作用域問題   

           timer=setInterval(fn,2);

            }else {

                clearInterval(timer);

                this.value = "點名";

            }

            

        }




 

        </script>

</body>

</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM