原生js 之 随机点名案例

需求:

1)点击开始按钮随机抽取数组的一个数据,放到页面中
2)点击结束按钮删除数组当前抽取的一个数据
3)当抽取到最后一个数据的时候,两个按钮同时禁用(只剩最后一个数据时不用再抽)

4)核心:利用定时器快速展示,停止定时器结束展示

用到的关键知识:

1)数组

2)获取DOM对象

3)全局/局部变量

4)按钮点击事件

5)定时器(开、关)

6)数学内置对象Math

页面效果展示:

 

关键源码: 

 <style>
    * {
      margin: 0;
      padding: 0;
    }

    h2 {
      margin-top: 100px;
      text-align: center;
    }

    .box {
      width: 450px;
      margin: 50px auto;
      display: flex;
      font-size: 20px;
      line-height: 40px;
    }

    .inner {
      width: 350px;
      height: 40px;
      border: 1px solid gray;
      color: green;
    }

    .btns {
      text-align: center;
    }

    .btns button {
      width: 120px;
      height: 35px;
      margin: 0 50px;
      cursor: pointer;
    }
  </style>

<body>
  <h2>随机点名</h2>
  <div class="box">
    <span>随机名:</span>
    <div class="inner">幸运儿</div>
  </div>
  <div class="btns">
    <button class="start">开始</button>
    <button class="end">结束</button>
  </div>
  <script>
    const arr = ['linsir', 'lxx', 'hyj', 'wyb', 'zly']
    // 定时器的全局变量
    let timerId = 0
    // 随机数的全局变量
    let random = 0
    const inner = document.querySelector('.inner')
    const start = document.querySelector('.start')
    //  添加点击事件
    start.addEventListener('click', function () {
      timerId = setInterval(function () {
        // 随机数
        random = parseInt(Math.random() * arr.length)
        inner.innerHTML = arr[random]
      }, 35)
      // 当数组里只有一个值 让两个按钮禁用
      if (arr.length === 1) {
        start.disabled = end.disabled = true
      }
    })

    const end = document.querySelector('.end')
    end.addEventListener('click', function () {
      clearInterval(timerId)
      // 结束后,删除掉当前抽取的那个数组元素
      arr.splice(random, 1)
      console.log(arr)
    })
  </script>
</body>

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linsir 一啵叶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值