<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.form{
width: 150px;
height: 150px;
margin: 0 auto;
}
.disp{
width: 150px;
height: 120px;
background-color: #9adcff;
border-radius: 10px 10px 0 0;
font-size: 25px;
line-height: 120px;
text-align: center;
}
button{
width: 75px;
height: 30px;
border: none;
background-color: #baffee;
border-radius: 0 0 0 10px;
}
button:nth-of-type(2){
border-radius: 0 0 10px 0 ;
}
button:hover{
background-color: #92fccd;
}
.hide{ /*点名完毕*/
width: 100%;
height: 30px;
color: #8dc0b3;
text-align: center;
border-radius: 0 0 10px 10px;
background-color: #baffee;
line-height: 30px;
display: none;
}
</style>
</head>
<body>
<div class="form">
<div class="disp">
随机点名
</div>
<button >开始</button><button disabled >暂停</button>
<div class="hide">点名完毕</div>
</div>
<script>
var stus =[];
var time;
var random;
var btn = document.querySelectorAll("button");
//添加学生
for (let i = 0; i < 5; i++){
stus[i] = "学生" + (i + 1);
}
//点击开始
btn[0].addEventListener("click",()=>{
//如果只有一个学生时
if (stus.length == 1){
document.querySelector(".disp").innerText = stus[0];
stus.splice(0,1);
//隐藏按钮
btn[0].style.display = "none";
btn[1].style.display = "none";
//显示结束语
document.querySelector(".hide").style.display = "block";
return;
}
//添加计时器,随机遍历
time = window.setInterval(()=>{
random = parseInt(Math.random() * stus.length);
document.querySelector(".disp").innerText = stus[random];
},100);
//交换按钮的单击权
btn[0].disabled = true;
btn[1].disabled = false;
});
//单击暂停
btn[1].addEventListener("click",()=>{
//删除当前计时器,使计时器停止
window.clearInterval(time);
//删除当前学生,避免下次被选
stus.splice(random,1);
//交换按钮的单击权
btn[1].disabled = true;
btn[0].disabled = false;
})
</script>
</body>
</html>
效果: