<!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>
// 数据数组
const arr = ['马超', '黄忠', '赵云', '关羽', '张飞']
let timeid = 0
//随机号 全局变量
let random = 0
// 业务1、开始按钮模块
const qs = document.querySelector('.qs')
// 1.1获取开始按钮对象
const start = document.querySelector('.start')
// 1.2添加点击事件
// 事件类型 点击鼠标 click 字符串
start.addEventListener('click', function () {
timeid = setInterval(function () {
random = parseInt(Math.random() * arr.length)
//把名字放进qs里面
qs.innerHTML = arr[random]
}, 35)
//数组只有一个值,禁用两个按钮
if (arr.length === 1){
start.disabled = end.disabled = true
}
})
// 2.关闭按钮模块
const end = document.querySelector('.end')
end.addEventListener('click', function () {
clearInterval(timeid)
arr.splice(random, 1)
console.log(arr)
})
</script>
</body>
</html>
03-随机点名案例
最新推荐文章于 2024-09-11 20:31:47 发布