需求:
1)点击开始按钮随机抽取数组的一个数据,放到页面中
2)点击结束按钮删除数组当前抽取的一个数据
3)当抽取到最后一个数据的时候,两个按钮同时禁用(只剩最后一个数据时不用再抽)
4)核心:利用定时器快速展示,停止定时器结束展示
用到的关键知识:
1)数组
2)获取DOM对象
3)全局/局部变量
4)按钮点击事件
5)定时器(开、关)
6)数学内置对象Math
页面效果展示:
关键源码:
<style>
* {
margin: 0;
padding: 0;
}
h2 {
margin-top: 100px;
text-align: center;
}
.box {
width: 450px;
margin: 50px auto;
display: flex;
font-size: 20px;
line-height: 40px;
}
.inner {
width: 350px;
height: 40px;
border: 1px solid gray;
color: green;
}
.btns {
text-align: center;
}
.btns button {
width: 120px;
height: 35px;
margin: 0 50px;
cursor: pointer;
}
</style>
<body>
<h2>随机点名</h2>
<div class="box">
<span>随机名:</span>
<div class="inner">幸运儿</div>
</div>
<div class="btns">
<button class="start">开始</button>
<button class="end">结束</button>
</div>
<script>
const arr = ['linsir', 'lxx', 'hyj', 'wyb', 'zly']
// 定时器的全局变量
let timerId = 0
// 随机数的全局变量
let random = 0
const inner = document.querySelector('.inner')
const start = document.querySelector('.start')
// 添加点击事件
start.addEventListener('click', function () {
timerId = setInterval(function () {
// 随机数
random = parseInt(Math.random() * arr.length)
inner.innerHTML = arr[random]
}, 35)
// 当数组里只有一个值 让两个按钮禁用
if (arr.length === 1) {
start.disabled = end.disabled = true
}
})
const end = document.querySelector('.end')
end.addEventListener('click', function () {
clearInterval(timerId)
// 结束后,删除掉当前抽取的那个数组元素
arr.splice(random, 1)
console.log(arr)
})
</script>
</body>