<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
h2 {
text-align: center;
}
.box {
width: 600px;
margin: 50px auto;
display: flex;
font-size: 25px;
line-height: 40px;
}
.qs {
width: 450px;
height: 40px;
color: red;
}
.btns {
text-align: center;
}
.btns button {
width: 120px;
height: 35px;
margin: 0 50px;
}
</style>
</head>
<body>
<h2>随机点名</h2>
<div class="box">
<span>名字是:</span>
<div class="qs">这里显示姓名</div>
</div>
<div class="btns">
<button class="start">开始</button>
<button class="end">结束</button>
</div>
<script src="./js/public.js"></script>
<script>
// 数据数组
const arr = ['马超', '黄忠', '赵云', '关羽', '张飞']
let id // 全局变量 在这个script标签中都可以被访问
let i
const start = document.querySelector('.start')
const qs = document.querySelector('.qs')
// 1. 1获取到 start按钮注册点击事件
start.addEventListener('click', function () {
// 先清除定时器
clearInterval(id)
// 1.2开启定时器
id = setInterval(function () {
// 调用随机函数
i = getRandom(0, arr.length - 1)
// 从数组中取出对应的数组元素
qs.innerHTML = arr[i]
}, 30)
// 3. 判断数组的长度是否等于1 将开始按钮与结束按钮设置为禁用的效果
if (arr.length === 1) start.disabled = end.disabled = true
})
// 2. 点击结束按钮时 停止定时器
// 2.1 获取到 class=end的按钮 注册点击事件
const end = document.querySelector('.end')
end.addEventListener('click', function () {
// 2.2 停止定时器
clearInterval(id)
// 2.3 删除被选中的这个元素
arr.splice(i, 1)
})
</script>
</body>
</html>
点击开始,随机点名
最新推荐文章于 2024-04-20 22:40:06 发布
这是一个使用HTML、CSS和JavaScript编写的简单随机点名应用。页面包含一个开始和结束按钮,以及显示被点名人姓名的区域。当点击开始按钮时,会每隔30毫秒随机从预定义的名字数组中选取一个姓名显示,并在数组长度减至1时禁用开始和结束按钮。点击结束按钮则清除定时器并从数组中移除当前选定的名字。
摘要由CSDN通过智能技术生成