js实现随机点名效果

设计好框架,这里就随便设计一个简单的框架

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>随机点名</title>
    <style>
        .random_qust{
            margin: 50px auto;
            text-align: center;
            width: 500px;
            height: 250px;
            background-color: pink;
            border:1px solid transparent
        }
        h2{
            margin-top: 30px;
            margin-bottom: 50px;
        }
        .button{
            display: flex;
            justify-content: space-around;
        }
    </style>
</head>
<body>
    <div class="random_qust">
        <h2>随机回答</h2>
        <h3>问题是:现在阶段来说:函数中的this指向谁</h3>
        <div class="button">
            <button class="sure">确定</button>
            <button class="end">结束</button>
        </div>
    </div>
</body>
</html>

 在Javascript中定义变量与对象

let question = ['赵云','刘备','关羽','马超','张飞']
let random //随机数
let time
const button_sure =  document.querySelector('.sure') //确定按钮
const button_end =  document.querySelector('.end') //结束按钮
const content = document.querySelector('.random_qust h3') //显示的内容(名字)

当点击确定按钮时,利用随机数对数据进行索引,并将其显示出来,每100ms随机显示一次;

当点击结束按钮时,停止即可。

代码如下:

button_sure.addEventListener('click',function () {
                time = setInterval(function () {
                random = parseInt(Math.random()*question.length)
                content.innerHTML = question[random]
            },100)
        })
        button_end.addEventListener('click',function () {
            content.innerHTML = question[random]
            clearInterval(time)
        })

结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值