最近学习了随机函数,今天就利用随机函数来做一个随机点名的案例吧
一、简洁版随机点名
1、跟着我一起,先学习一个随机函数的代码
<script>
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
</script>
2、接下来我们一起来做个案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
height: 40px;
width: 200px;
border: 1px solid pink;
text-align: center;
line-height: 40px;
}
</style>
</head>
<body>
<div></div>
<button>点击点名</button>
<script>
// 1、获取元素
let box = document.querySelector('div')
let btn = document.querySelector('button')
// 2、随机函数
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
let arr = ['小红', '小胡', '小马', '小王', '可乐']
// 3、事件监听
btn.addEventListener('click', function () {
// 随机数字
let random = getRandom(0, arr.length - 1)
box.innerHTML = arr[random]
// 删除数组元素 splice(从哪里删,删几个)
arr.splice(random, 1)
// 当抽到最后一个时 按钮禁用
if (arr.length === 0) {
btn.disabled = true
btn.innerHTML = '已经抽完了'
}
})
</script>
</body>
</html>
二、升级版随机点名(用到了定时器)
<!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>
// 数据数组
let arr = ['小红', '小胡', '小马', '小王', '可乐']
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
// 1、获取元素 两个按钮+div
let start = document.querySelector('.start')
let end = document.querySelector('.end')
let qs = document.querySelector('.qs')
// 2、设置开始按钮事件
// timer要设置为全局变量
let timer = 0
// random要设置为全局变量
let random = 0
start.addEventListener('click', function () {
// 随机抽取数字 开启定时器
timer = setInterval(function () {
random = getRandom(0, arr.length - 1)
qs.innerHTML = arr[random]
}, 15)
// 如果到了最后一个禁用按钮
if (arr.length === 1) {
start.disabled = end.disabled = true
}
})
// 3、设置结束按钮事件
end.addEventListener('click', function () {
// 关闭定时器
clearInterval(timer)
// 删除重复元素
arr.splice(random, 1)
})
</script>
</body>
</html>
好了,今天的案例就到这里,我们下期见