1.实现:
点击开始按钮 - > 名字开始在页面滚动 - > 点击结束按钮 - > 停止滚动出现随机名字 - > 在数组中删除对应数据 - > 数据为1 - > 禁用所有按钮
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<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>
</head>
<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>
<script>
let nameArr = ['赵一','钱二','孙三','李四','周五','吴六']
let theStart = document.querySelector('.start')
let theEnd = document.querySelector('.end')
let theQs = document.querySelector('.qs')
let time
let num
function rand(min,max) {
// return口诀:return到当前函数 调用的地方 但是发现当前函数没有调用 所以不能返回出去
return Math.floor(Math.random() * (max - min +1) + min)
}
theStart.addEventListener('click',function() {
clearInterval(time) //防止多次点击计时器重复调用
time = setInterval(function() {
num = rand(0,nameArr.length - 1)
theQs.innerHTML = nameArr[num]
},100)
// 注意:点击开始 如果只剩一个 直接禁用两个按钮 不用再点击结束
if(nameArr.length === 1) {
theStart.disabled = true
theEnd.disabled = true
}
})
theEnd.addEventListener('click',function(){
clearInterval(time)
nameArr.splice(num,1)
})
</script>
</body>
</html>