效果图
搭建基本结构
html
<div class="box">
<h2>随机点名</h2>
<div class="name">
<h4>幸运儿是:</h4>
<p>小吴</p>
</div>
<div class="buttom">
<button class="start">开始</button>
<button class="end">结束</button>
</div>
</div>
css
* {
margin: 0;
padding: 0;
}
.box {
width: 400px;
height: 150px;
margin: 100px auto;
border-radius: 15px;
border: none;
background-color: skyblue;
}
h2 {
text-align: center;
}
.buttom {
position: relative;
}
.start {
position: relative;
top: 10px;
left: 150px;
width: 60px;
height: 25px;
border: none;
border-radius: 15px;
cursor: pointer;
}
.end {
position: relative;
top: 10px;
right:-150px;
width: 60px;
height: 25px;
border: none;
border-radius: 15px;
cursor: pointer;
}
.name {
width: 100%;
margin: 30px 0px 10px;
float: left;
}
p {
float: left;
}
h4 {
float: left;
}
js
先声明一个数组,数组里面放入将要被点名人的名单
// 声明数组
const nameArr = ['张三','尤琪琪','尤桑','嘤嘤怪','小吴','李四','王五']
获取开始对象(start)
// 获取开始对象
const start=document.querySelector('.start')
const p=document.querySelector('p')
定义全局变量
// 作用域影响,使用全局变量
let k =0
let random=0
给start开始按钮绑定点击事件
用到了setInterval定时器,给定时器取名为k,方便后面清除
在任何使用随机的情况下,离不开Math.random()和Math.floor()
random()可以随机返回一个小数,取值范围为[0,1)
Math.floor()俗称地板函数,向下取整。例:Math.floor(3.1)=Math.floor(3.9)=3
将Math.random()随机小数 X 数组长度,向下取整,就可以获得随机数
将获得的随机数当作数组对象下标即可起到随机点名效果
start.addEventListener('click',function() {
// 定时器开启
k = setInterval(function(){
// 取随机数
random=Math.floor(Math.random()*nameArr.length)
// 更换p标签内容
p.innerHTML=nameArr[random]
},300)
结束按钮
清除定时器即可,并且使用splice()方法,将已经被点过名的人剔除后续随机选人名单中,避免重复点名
splice(从哪个位置删除,删几个)
// 结束按钮
const end=document.querySelector('.end')
// 监听
end.addEventListener('click',function() {
// 定时器关闭
clearInterval(k)
// 删数组中的对象
nameArr.splice(random,1)
})
最后给开始按钮加个优化,当数组中只有最后一个人的时候,禁用按钮
if(nameArr.length===1) {
start.disabled=end.disabled=true
}