简易版随机点名

<!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: 500px;
            height: 300px;
            margin: 100px auto;
        }
        .title {
            display: flex;
            width: 500px;
            height: 100px;
        }
        .title span {
            margin: 20px;
        }
        button {
            margin: 30px;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="title">
            <span>随机点名:</span>
            <span class="qs">显示的名字</span>
        </div>
        <div class="btn">
            <button>开始</button>
            <button>结束</button>
        </div>
    </div>
</body>
</html>
 <script>
        let arr = ['小花', '小丽', '小刚', '小明', '小华', '小华', '小晓']
        // 1. 点击开始按钮,开启定时器
        // 获取元素
        let qs = document.querySelector('.qs')
        let start = document.querySelector('.btn button:nth-child(1)')
        let end = document.querySelector('.btn button:nth-child(2)')
        let timer
        let randomIndex
        // 监听事件
        start.addEventListener('click',function() {
            clearInterval(timer)  // 连续点击开始按钮,第二个的定时器会覆盖第一个的定时器,导致第一个定时器无法停止,所以开启定时器后要先停止定时器
            timer = setInterval(function() {
                // 生成一个随机索引号
            // let randomIndex = Math.floor(Math.random() * (arr.length - 1 - 0 + 1) + 0)
            randomIndex = Math.floor(Math.random() * arr.length)
            // 将数组中的随机元素赋值给div,修改div的内容
            qs.innerHTML = arr[randomIndex]
            },100)
        })
        // 2. 点击结束按钮,结束定时器
        end.addEventListener('click',function () {
            clearInterval(timer)
            // 删除已点到的名字
            arr.splice(randomIndex, 1)
            console.log(arr);
            // 判断 当数组长度为0时,开始和结束按钮禁用
            if (arr.length === 0) {
                start.disabled = true
                end.disabled = true
            }
          })
        
    </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值