效果在线展示(可直接fork后修改JS里面姓名列表自用):
网页源码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>随机点名</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #60AEEF;
}
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
z-index: 1;
}
h1 {
font-size: 4rem;
color: #fff;
text-shadow: 0 0 10px rgba(0,0,0,0.5);
margin-bottom: 1rem;
}
#name-display {
font-size: 3rem;
color: #fff;
text-shadow: 0 0 10px rgba(0,0,0,0.5);
margin-bottom: 2rem;
}
button {
font-size: 2rem;
padding: 1rem 2rem;
background-color: transparent;
border: 2px solid #fff;
color: #fff;
cursor: pointer;
transition: all 0.3s ease-in-out;
}
button:hover {
background-color: #fff;
color: #000;
}
.result {
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
background-color: blue;
color: white;
font-weight: bold;
padding: 1rem 2rem;
font-size: 3rem;
display: none;
}
/* 自适应 */
@media only screen and (max-width: 768px) {
.result {
font-size: 2rem;
padding: 0.5rem 1rem;
}
}
}
</style>
</head>
<body>
<div class="container">
<h1>随机点名器</h1>
<p id="name-display">准备好了吗?</p>
<button id="start-button">开始</button>
<div class="result"></div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
var names = ["张三", "李四", "王五", "赵六", "刘七"];
var nameDisplay = document.getElementById("name-display");
var startButton = document.getElementById("start-button");
var resultBox = document.querySelector(".result");
var timer, index;
startButton.addEventListener("click", function() {
index = 0; // 初始化名字索引
nameDisplay.innerText = ""; // 清空名字显示区域
clearInterval(timer); // 清除之前的定时器
// 设置一个新的定时器循环遍历所有名字
timer = setInterval(function() {
if (index >= names.length) { // 如果已经循环到最后一个名字
clearInterval(timer); // 清除定时器
var selectedName = names[Math.floor(Math.random() * names.length)]; // 选择随机名字
nameDisplay.innerText = selectedName; // 将随机名字显示在名字显示区域中
} else {
nameDisplay.innerText = names[index]; // 将当前索引对应的名字显示出来
index++; // 名字索引增加一
}
}, 50);
});
});
</script>
</body>
</html>