骨架
<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>
</body>
css样式
<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: 35px;
margin: 0 50px;
}
</style>
js
<script>
// 数据数组
const arr = ['马超', '黄忠', '赵云', '关羽', '张飞']
// 定时器的全局变量
let timerId = 0
let index = 0
// 获取开始按钮对象
const start = document.querySelector(`.start`)
// 获取结束按钮对象
const end = document.querySelector(`.end`)
// 开始按钮模块
const qs = document.querySelector(`.qs`)
// 添加点击事件
start.addEventListener(`click`, function () {
clearInterval(timerId)
timerId = setInterval(function () {
// 随机数
index = Math.floor(Math.random() * arr.length)
qs.innerHTML = arr[index]
}, 10)
})
// 关闭按钮模块
end.addEventListener(`click`, function () {
clearInterval(timerId)
// 结束了,可以删除掉当前抽取的那个数组元素
arr.splice(arr[index], 1)
// 如果数组里面只有一个值了,还需要抽取吗? 不需要 让两个按钮禁用就可以
if (arr.length === 0) {
start.disabled = true
end.disabled = true
}
})
</script>