<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;
}
.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>开始</button>
<button>结束</button>
</div>
<!--
<button>普通按钮</button> -->
<script>
// 1、点击随机点名
// 2、点击结束停止随机点名
// 数据
let arr = ['张三丰', '张无忌', '乔峰', '柳霞', '金毛狮王', '张飞', '赵云', '貂蝉'];
// 1、获取元素
let qs = document.querySelector('.qs');
let start = document.querySelector('.btns button:nth-child(1)');
let end = document.querySelector('.btns button:nth-child(2)');
// 因为局部变量不能在别的地方使用,所以这两个变量申明为全局变量
let timer;
let randomIndex;
// 2、监听事件
start.addEventListener('click', function () {
// 点击开启定时器之前,先把上一个定时器清楚,永远保存timer只有一个
clearInterval(timer);
// 启动定时器
timer = setInterval(function () {
// arr[值]
// 随机的索引值
randomIndex = Math.floor(Math.random() * arr.length);
// 去数组中随机取值
// 放到div中
qs.innerText = arr[randomIndex];
}, 50);
});
end.addEventListener('click', function () {
// 1、停止定时器
clearInterval(timer);
// 2、去数组删除刚才的那个值
arr.splice(randomIndex, 1);
// 如果数组里面没有值,那么就禁用两个按钮
if (arr.length <= 0) {
start.disabled = true;
end.disabled = true;
}
});
</script>
</body>
WebAPI-随机点名小案例
最新推荐文章于 2023-04-19 11:40:43 发布