1. 程式人生 > 實用技巧 >JS 實現雙色球搖獎效果

JS 實現雙色球搖獎效果

程式碼:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        button {
            font-size: 20px;
            padding:
5px 30px; margin-left: 20px; } span { width: 100px; height: 100px; border-radius: 50px; background-color: red; display: inline-block; margin-top: 30px; margin-left: 20px; color: white
; font-size: 40px; text-align: center; line-height: 100px; } </style> </head> <body> <!-- --> <button>開始</button> <button>停止</button> <br> <span id="aaa"></span> <span
></span> <span></span> <span></span> <span></span> <span></span> <span style="background-color: #06c;"></span> <script> //1.獲取元素 var btns = document.getElementsByTagName("button"); var spans = document.getElementsByTagName("span"); //4.宣告一個變數 用來記錄 當前要停止的小球的索引 var n = 0; var timer = null; //2.點選 開始 讓所有小球中的內容 進行自動切換 btns[0].onclick = function () { //0-30 timer = setInterval(function () { //切換一次的程式碼 for (var i = n; i < spans.length; i++) { var ran = parseInt(Math.random() * 31); spans[i].innerText = ran; } }, 50) } //3.點選 停止按鈕 讓正在切換的第一個小球停下來 btns[1].onclick = function () { setTimeout(function () { n++;//1 2 //1.當全部停止之後 要清除定時器 if(n>=7){ clearInterval(timer); n = 0;//2.在停止之後 可以重新開始的 } }, 500) } </script> </body> </html>