代码:
<!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> <style> .box { width: 200px; height: 50px; display: flex; justify-content: center; align-items: center; border: 1px solid red; } </style> </head> <body> <div class="box">幸运儿</div> <button class="start">开启随机点名</button> <button class="stop">结束随机点名</button> <script> // 随机数公式 function getRandom(min = 0, max = 1) { return Math.floor(Math.random() * (max - min + 1)) + min } // 名单数组 let array = ['赵云', '黄忠', '关羽', '张飞', '马超', '刘备', '曹操'] // 获取事件源 let box = document.querySelector('.box') let start = document.querySelector('.start') let stop = document.querySelector('.stop') let timerId let random // 添加事件监听 start.addEventListener('click', function(){ // console.log('ok') // 开启定时器 timerId = setInterval(function(){ // 获取随机数 random = getRandom(0, array.length - 1) // console.log(random); // console.log(array[random]) // 在方框中滚动姓名 box.innerHTML = array[random] }, 100) }) stop.addEventListener('click', function(){ // 清理定时器 clearInterval(timerId) // 删除抽过的姓名 array.splice(random, 1) // 如果数组为空,禁用按钮 if(array.length === 0){ start.disabled = true stop.disabled = true } }) </script> </body> </html>
效果图:
web API-事件基础-随机点名滚动版
最新推荐文章于 2024-11-03 16:40:52 发布