<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #ddd;
}
.container {
position: relative;
margin: 100px auto;
width: 620px;
height: 480px;
background-color: rgb(89, 138, 218);
border-radius: 20px;
border: 10px dashed black;
}
.container h2 {
text-align: center;
color: white;
line-height: 80px;
height: 80px;
font-family: 宋体;
}
.container .classmateName {
background-color: white;
height: 280px;
width: 540px;
margin: 0 auto;
line-height: 280px;
text-align: center;
font-size: 50px;
font-weight: bold;
}
.container .control {
width: 540px;
margin: 0 auto;
text-align: center;
line-height: 80px;
vertical-align: middle;
}
.container .control label {
font-size: 24px;
display: none;
}
.container .control label input {
width: 50px;
height: 60px;
vertical-align: middle;
font-size: 20px;
padding-left: 10px;
}
.container .control .left,
.container .control .right {
height: 60px;
width: 100px;
font-size: 20px;
}
.container .control .left {
margin-right: 80px;
}
</style>
<div class="container">
<h2>随机点名器</h2>
<p class="classmateName"></p>
<div class="control">
<label>
随机人数:<input type="text" value="1">
</label>
<button class="left">
开始
</button>
<button class="right">
结束
</button>
</div>
</div>
<script>
// 0. 第三组学生
let studentList =[`小红`,`小黄`,`小安`,`小绿`,`小四`]
// 1. 获取元素
const leftBtn = document.querySelector('.left')
const rightBtn = document.querySelector('.right')
const p = document.querySelector('.classmateName')
// 2. 声明定时器名
let timerId = 0
let index = 0
// 3. 封装函数-用于重置
function resetFn(isStart = false, isEmpty = false) {
clearInterval(timerId)
leftBtn.disabled = (isEmpty ? isEmpty : isStart)
rightBtn.disabled = (isEmpty ? isEmpty : !isStart)
if (isEmpty) {
alert('已经抽完所有学生')
}
}
// 4. 点击"开始"按钮, 触发定时器, 重置disabled属性
leftBtn.addEventListener('click', function () {
resetFn(true, false)
timerId = setInterval(function () {
index = Math.floor(Math.random() * studentList.length)
p.innerText = studentList[index]
}, 40)
})
// 5. 点击"结束"按钮, 关闭定时器, 重置disabled属性
rightBtn.addEventListener('click', function () {
studentList.splice(index, 1)
const isEmpty = studentList.length === 0
resetFn(false, isEmpty)
})
</script>