需求:分为上下两个部分,上方为显示区域,下方为控制区域。显示区域显示基地所有成员的工号和姓名,控制区域由开始和结束两个按钮组成。点击开始按钮,显示区域里的内容开始滚动,点击结束按钮,内容滚动停止,随机显示一位成员的工号和姓名。
实现原理:
1.首先设置名字区域和按钮区域
2.利用数组设置后台数据将工号和姓名填入
3.设置内容滚动函数,将速度定为100ms
4.绑定点击事件使暂停效果生效
<!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>
<style>
/* 设置页面背景色 */
body {
background-color: aliceblue;
}
/* 点名区域样式设置 */
h1 {
text-align: center;
}
.box {
width: 1000px;
height: 150px;
margin: 0 auto;
margin-top: 100px;
clear: both;
position: relative;
}
#span {
position: absolute;
width: 180px;
height: 70px;
line-height: 70px;
font-size: 20px;
text-align: center;
background-color: antiquewhite;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.but {
width: 300px;
height: 40px;
margin-left: 40%;
margin-top: 40px;
}
#start {
width: 100px;
height: 40px;
outline: none;
border: 1px solid gray;
border-radius: 6px;
font-size: 16px;
margin-left: 60px;
}
#btn {
width: 100px;
height: 40px;
margin-left: 20px;
outline: none;
border: 1px solid gray;
border-radius: 6px;
font-size: 16px;
}
</style>
</head>
<body>
<!-- HTML结构 -->
<!-- 标题部分 -->
<h1>随机点名系统</h1>
<!-- 点名区域 -->
<div class="box" id="box">
<!-- 名字显示区域 -->
<span id="span"></span>
</div>
<!-- 点名按钮 -->
<div class="but">
<input type="button" id="start" value="开始点名" />
<input type="button" id="btn" value="暂停" />
</div>
<script>
// 模拟后台数据
var arr = ["02010102梁克锦", "02010103骆文浩", "02010104方海英", "02010105廖玉洁", "02010106张震宇", "02010107李炫宇", "02010108李舜禹",
"02010109李建民", "02010110佟冠衡", "02010111李奥", "02010112颜宏鑫", "02010113卢盛泽", "02010114鲁飞扬", "02010115李俊达", "02010116李成基" ];
// 获取名字显示区域
var text = document.getElementById('span');
// 获取暂停按钮
var btn = document.getElementById('btn');
// 获取开始点名按钮
var start = document.getElementById('start');
var timer;
start.addEventListener('click', function () {
clearInterval(timer);
timer = setInterval(function () {
var number = parseInt(Math.random() * arr.length);
text.innerText = arr[number];
}, 100);
}, false);
// 暂停点名事件的实现
btn.onclick = function () {
clearInterval(timer);
}
</script>
</body>
</html>
效果:
QQ录屏20230112114213