<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
*{
margin: 0;
padding: 0;
}
h3{
text-align: center;
font-weight: 400;
}
.bx{
margin: 0 auto;
}
.dianmingplace{
margin-top: 5px;
width: 150px;
height: 30px;
text-align: center;
border: 1px solid pink;
}
.cz{
margin-top: 25px;
width:250px;
background-color:palevioletred;
text-align: center;
}
.cz .start{
width: 90px;
margin-right: 15px;
border-radius: 7px;
}
.cz .start:hover{
background-color: aquamarine;
}
.cz .end{
width: 90px;
margin-left: 15px;
border-radius: 7px;
}
.cz .end:hover{
background-color:red;
}
</style>
<body>
<h3 class="bx">随机点名</h3>
<div class="dianmingplace bx">
</div>
<div class="cz bx">
<button class="start">开始点名</button>
<button class="end" >停止</button>
</div>
<script>
// 新建一个数组存储点名的对象
let arr=['sdd','sdx','cxv','sf','xc']
// 获取对象
let dianming=document.querySelector('.dianmingplace')
let start=document.querySelector('.start')
let end=document.querySelector('.end')
// 全局变量
let random=0
let timer=0
//取随机数
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
//开始点名的监听事件
start.addEventListener('click',function(){
// 设置定时器,让数据有屏闪的效果
timer=setInterval(function(){
random=getRandom(0,arr.length-1)
dianming.innerHTML=arr[random]
},300)
// 当数据的长度为1时(即数组的长度为1),需要禁用两个按钮
if(arr.length === 1){
start.disabled=true
end.disabled=true
}
})
//停止点名的监听事件
end.addEventListener('click',function() {
// 清除定时器,停止随机取名
clearInterval(timer)
//删除当前名字,避免重复取到
arr.splice(random,1)
})
</script>
</body>
</html>
效果图