JS随机点名案例

pink老师 APls Day2

思路:

  1. 创建一个数组容纳随机姓名
  2. 运用random随机函数获得一个随机值,且随机值不重复
  3. 将随机值对应的姓名进行本文更换
  4. 按钮与定时器的关闭
  5. 数量与按钮的关闭
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>随机点名案例</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        h2 {
            text-align: center;
        }
        .box {
            width: 600px;
            margin: 50px auto;
            display: flex;
            font-size: 25px;
            line-height: 40px;
        }
        .qs {
            width: 450px;
            height: 40px;
            color: red;
        }
        .btns {
            text-align: center;
        }
        .btns button {
            width: 120px;
            height: 30px;
            margin: 0 50px;
        }
    </style>
</head>
<body>
    <h2>随机点名</h2>
    <div class="box">
        <span>名字是:</span>
        <div class="qs">姓名</div>
    </div>
    <div class="btns">
        <button class="start">开始</button>
        <button class="end">结束</button>
    </div>
    <script>
        const arr = ['黄忠', '张三', '李四', '王五', '张飞', '关羽', '赵云', '孙策']
        //在外面声明定时器的全局变量
        let timerId = 0
        let random = 0
        const qs = document.querySelector('.qs')
        // 1.1获取开始按钮
        const start = document.querySelector('.start')
        // 1.2添加点击事件
        start.addEventListener('click', function(){
            //局部变量,出函数不可使用
            timerId = setInterval(function(){
                //生成一个随机数
            random = parseInt(Math.random() * arr.length)
            // console.log(random)
            // console.log(arr[random])
            // 将获取的随机数对应的随机姓名进行文本更换
            qs.innerHTML = arr[random]
        }, 35)

        //如果数组 中只剩下一个值,禁用两个按钮
        if (arr.length === 1) {
            // start.disabled = true  //禁用
            // end.disabled = false
            start.disabled = end.disabled = true
        }
    })
        // 2.点击按钮关闭定时器
        const end = document.querySelector('.end')
        end.addEventListener('click', function() {
            // console.log('1234')
            clearInterval(timerId)
            //删除当前抽取的元素
            arr.splice(random, 1)
            console.log(arr)
        })
    </script>
</body>
</html>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值