JS實現抽獎

九宮格隨機抽獎功能實現:在選擇的時候方格的輪轉速度先慢後快再慢的效果數組

代碼以下:dom

 <div class="container">
        <div class="block1 block">小米筆記本</div>
        <div class="block2 block">iPhoneX</div>
        <div class="block3 block">PS4遊戲機</div>
        <div class="block4 block">謝謝參與</div>
        <div class="block5 block">開始抽獎</div>
        <div class="block6 block">索尼電視機</div>
        <div class="block7 block">西門子冰箱</div>
        <div class="block8 block">老闆抽油煙機</div>
        <div class="block9 block">空氣淨化機</div>
    </div>
<style>
        .container {
            width: 600px;
            height: 600px;
            border: 1px solid;
            display: flex;
            flex-wrap: wrap;
            margin: 100px auto;
        }

        .block {
            width: 33.33%;
            height: 33.33%;
            outline: 1px solid black;
            text-align: center;
            line-height: 200px;
            font-size: 26px;
        }

        .block5 {
            background-color: skyblue;
            cursor: pointer;
        }
    </style>
<script>
        let blocks = document.getElementsByClassName("block");
        // 數組存放的是盒子的下標,按照順時針的順序
        let arr = [0, 1, 2, 5, 8, 7, 6, 3], i = 0, count = 0, stopTimer;
        let rand = Math.floor(Math.random() * 8 + 50); // 給出一箇中止計時器的隨機數 count的值等於這個隨機數時中止計時器
        let around = function () {
            // 將其餘盒子都變爲白色
            for (let j = 0; j < arr.length; j++) {
                blocks[arr[j]].style.background = "white";
            }
            // 這裏blocks的取值爲 blocks[0] blocks[1] blocks[2] blocks[5] blocks[8] blocks[7] blocks[6] blocks[3]
            // 將當前arr[i]值所對應的盒子修改成粉色
            blocks[arr[i]].style.background = "pink";
            i++; 
            // 重製i的值
            if (i === arr.length) {
                i = 0;
            }
            count++; // count是一個計數器 根據count的值來調整速度
            // 下面的4個if根據count的值來關閉計時器和重啓計時器 改變計時器的時間間隔
            if (count === 5 || count === 45) {
                clearInterval(stopTimer);
                stopTimer = setInterval(around, 200);
            }
            if (count === 10 || count === 35) {
                clearInterval(stopTimer);
                stopTimer = setInterval(around, 100);
            }
            if (count === 15) {
                clearInterval(stopTimer);
                stopTimer = setInterval(around, 50);
            }
            // 當等於上面的隨機數時,中止計時器
            if (count === rand) {
                clearInterval(stopTimer);
            }
        }
        // 給開始按鈕綁定點擊事件 點擊後執行 around 
        let start = function () {
            blocks[4].removeEventListener("click", start); // 當用戶點擊了開始按鈕後 必需要移除該事件 防止用戶重複點擊
            stopTimer = setInterval(around, 300);
        }
        blocks[4].addEventListener("click", start);
    </script>

實現圖:flex

相關文章
相關標籤/搜索