效果图
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>练习:随机点名</title>
<style>
div {
margin: 50px auto;
width: 500px;
height: 300px;
border: 3px solid #ccc;
text-align: center;
}
div p {
margin: 50px;
font-size: 50px;
color: red;
}
div button {
margin: 20px;
width: 90px;
height: 40px;
}
</style>
</head>
<body>
<div>
<h2>随机点名</h2>
<p>???</p>
<button class="start">开始</button>
<button class="end" disabled>结束</button>
</div>
<script>
const arr = ['张三', '李四', '王五', '赵六', '冯七']
const start = document.querySelector(".start")
const end = document.querySelector(".end")
const p = document.querySelector("p")
let alter = 0
let num = 0
start.addEventListener("click", () => {
alter = setInterval(() => {
num = Math.floor(Math.random() * arr.length)
p.innerText = arr[num]
}, 25)
start.disabled = true
end.disabled = false
})
end.addEventListener("click", () => {
clearInterval(alter)
arr.splice(num, 1)
if (arr.length === 1) {
start.disabled = true
end.disabled = true
} else {
end.disabled = true
start.disabled = false
}
})
</script>
</body>
</html>