一、需求
1、点击开始按钮,姓名随机切换
2、点击结束按钮,姓名停止切换,此时显示的姓名即为被抽中者
3、同一个人不能被重复抽中
二、代码素材
以下是缺失JS部分的代码,感兴趣的小伙伴可以先自己试着写一写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>随机点名</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
position: relative;
box-sizing: border-box;
margin: 50px auto;
border: 2px solid #ccc;
padding: 20px;
width: 500px;
height: 200px;
text-align: center;
}
.box h3 {
line-height: 75px;
}
.box button {
position: absolute;
bottom: 30px;
width: 60px;
height: 30px;
}
.box .start {
left: 130px;
}
.box .over {
right: 130px;
}
</style>
</head>
<body>
<div class="box">
<h2>随机点名</h2>
<h3>姓名:马嘉祺</h3>
<button class="start">开始</button>
<button class="over">结束</button>
</div>
<script>
const arr = ['马嘉祺', '丁程鑫', '宋亚轩', '严浩翔', '刘耀文', '贺峻霖', '张真源']
</script>
</body>
</html>
三、算法思路
算法思路非常简单,就是分别为开始按钮和结束按钮绑定点击事件,然后触发开始按钮就开启定时器,触发结束按钮就终止定时器,就这么简单……
四、完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>随机点名</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
position: relative;
box-sizing: border-box;
margin: 50px auto;
border: 2px solid #ccc;
padding: 20px;
width: 500px;
height: 200px;
text-align: center;
}
.box h3 {
line-height: 75px;
}
.box button {
position: absolute;
bottom: 30px;
width: 60px;
height: 30px;
}
.box .start {
left: 130px;
}
.box .over {
right: 130px;
}
</style>
</head>
<body>
<div class="box">
<h2>随机点名</h2>
<h3>姓名:马嘉祺</h3>
<button class="start">开始</button>
<button class="over">结束</button>
</div>
<script>
const arr = ['马嘉祺', '丁程鑫', '宋亚轩', '严浩翔', '刘耀文', '贺峻霖', '张真源']
const h3 = document.querySelector('.box h3')
const start = document.querySelector('.start')
const over = document.querySelector('.over')
let timer
let rand
start.addEventListener('click', () => {
start.disabled = 1
over.disabled = 0
timer = setInterval(() => {
rand = Math.floor(Math.random() * arr.length)
h3.innerHTML = `姓名:${arr[rand]}`
}, 100);
})
over.addEventListener('click', () => {
start.disabled = 0
over.disabled = 1
clearInterval(timer)
//数组长度为 1 时,禁用按钮
if (arr.length === 1)
start.disabled = over.disabled = 1
else
arr.splice(rand, 1)
})
</script>
</body>
</html>