一、成果图
二、实现步骤
1.实现思路
- 需求解析——当用户点击开始点名时,橘色文本框会随之出现姓名,当然,用户也可自行暂停。
- 实现思路——
- 可将学生姓名存储于一个数组中模拟后台数据,在循环中遍历数组。
- 若要实现每一个学生姓名的出现频率是随机的就需要使用 random 随机函数(关于这一点在前文有介绍到).
- 若要实现橘色文本框中姓名的不断出现可结合使用定时器即可实现。
2.实现过程
2.1 HTML结构
<!-- 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>
2.2 CSS样式
<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: 100px;
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>
2.3 JS部分
<script>
// 模拟后台数据
var arr = ["吴纪伟", "马帅", "刘中华", "朱静远", "马力", "王一之", "陈浩然", "姚晨宇",
"何正汉", "朱晋晋", "童俊涛", "陈旭", "李嘉莹", "王仕丹", "徐军", "卢心愿", "彭代宏", "王坚"
, "胡海龙", "鲍风雨", "杨健健", "杨东", "孙富财", "王正祥", "刘友瑞", "汪海龙", "樊明辉", "陈全宏"
];
// 获取名字显示区域
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];
}, 200);
}, false);
// 暂停点名事件的实现
btn.onclick = function () {
clearInterval(timer);
}
</script>
总结
以上就是今日所要分享的内容,就此停笔吧,最后依旧诚挚祝福屏幕前的你平安喜乐~,拜