滚动抽奖(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>
</head>
<body>
    <h1>谁最美?</h1>
    <button onclick="start()">开始</button>
    <button onclick="end()">结束</button>
    <h2 id="title"></h2>
    <script>
        var arr = ['宝贝','小宝贝','小可爱','臭狗屎','小乖','楠哥','小仙女']
        // 通过id拿到h2的标签
        var title = document.getElementById('title')
        var timer = null // null 是变量有值,只不过值为空  undefined压根就没有值

        function start (){
                // 此处不能var timer,因为timer在局部变量里面
                timer = setInterval(function(){
                var index = Math.floor(Math.random()*arr.length)
                // 把arr[index]的内容放到h2标签里面
                title.innerHTML = arr[index]
            },100)
        }
        function end(){
            // 通过timer来控制开始按钮
            clearInterval(timer)
        }


    </script>
</body>
</html>
发布了60 篇原创文章 · 获赞 3 · 访问量 533

猜你喜欢

转载自blog.csdn.net/dfc_dfc/article/details/105521631