大致思路
1将所有数组转为字符串再转为对象 2获取元素div p 以及按钮 3将下标设为0,将定时器,延时器定义为空,将数组的长度定义为num, 4,定义一个点击事件 当鼠标点击时,清空定时器,延时器,然后进行判断 ,如果num<1,证明已经全部点名完毕,不再执行下一步 else 设置一个定时器的箭头函数 定义index等于math.fllor(math.radom()*num),这是为了将下标进行随机选取 然后让获取的名字的类名.innerHTML等于数组【index】,最后延时300毫秒 然后定义一个延时器的箭头函数 清除定时器,然后运用 对象.splice(index,1)进行删除当前选中下标,最后设置定时器为null,再加上延时3000毫秒
css
.box {
width: 200px;
height: 200px;
background-color: salmon;
transform: translate(600px, 200px);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.btn {
width: 100px;
height: 50px;
border-radius: 10px;
}
html
<div class="box">
<p>点名器</p>
<button class="btn">开始</button>
</div>
javascript
var arrName = ["赵艳", "林明", "郭秀英", "马军", "王艳", "方娟", "林勇", "廖明", "程敏", "曾秀英", "马平", "陆强", "张军", "崔涛", "石秀英", "武丽", "谭刚", "蒋秀英", "杨杰", "陈秀兰"]
var newArr = JSON.parse(JSON.stringify(arrName))
var ps = document.querySelector("p")
// console.log(ps);
var btn = document.querySelector(".btn")
var timer, timers = null;
var index = 0;
var num = newArr.length;
btn.onclick = function () {
clearInterval(timer)
clearInterval(timers)
if (num < 1) {
confirm("全部点名完毕")
}
timer = setInterval(() => {
index = Math.floor(Math.random() * num)
ps.innerHTML = arrName[index]
console.log(arrName[index]);
}, 100)
btn.innerHTML = "点名中..."
timers = setTimeout(() => {
clearInterval(timer)
newArr.splice(index, 1)
timer = null
btn.innerHTML = "开始点名"
}, 3000)
}