需求
分为上下两个部分,上方为显示区域,下方为控制区域。显示区域显示基地所有成员的工号和姓名,控制区域由开始和结束两个按钮组成。点击开始按钮,显示区域里的内容开始滚动,点击结束按钮,内容滚动停止,随机显示一位成员的工号和姓名。
原理
设置随机选择函数,利用系统的Math.random取得随机值,给开始按钮绑定点击事件,设置间隔定时器,每100毫秒,执行一次。给结束按钮绑定点击事件,执行清除定时器指令。
<!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>
body{
width: 800px;
height: 600px;
margin: 100px auto;
border: 2px solid rgb(21, 2, 5);
}
#top{
display: flex;
flex-wrap: wrap;
justify-content: center;
height: 500px;
border: 2px solid black;
}
.name{
width: 100px;
height: 30px;
text-align: center;
line-height: 30px;
background-color: rgba(216, 197, 232, 0.788);
margin: 20px;
border-radius: 30px
}
/* #bottom{
} */
#bottom button{
width: 150px;
height: 60px;
margin: 20px 120px;
border-radius: 60px;
font-size: 20px;
}
#bottom button:hover{
background-color: rgb(90, 75, 105);
}
</style>
</head>
<body>
<div id="top"></div>
<div id="bottom">
<button id="start">START</button>
<button id="end">END</button>
</div>
</body>
<script>
var content=document.getElementById("top")
var allName=[
"01010101","01010102","01010102","01010102",
"01010102","01010102","01010102","01010102",
"01010102","01010102","01010102","01010102",
"01010102","01010102","01010102","01010102",
"01010102","01010102","01010102","01010102"]
for(let i=0;i<allName.length;i++){
var child=document.createElement("div")
child.className="name"
child.innerHTML=allName[i]
content.appendChild(child)
}
var start=document.getElementById("start")
var end=document.getElementById("end")
start.onclick=function(){
timer=setInterval(run,100)
}
end.onclick=function(){
clearInterval(timer)
}
run=function(){
for(let m=0;m<content.children.length;m++){
content.children[m].style.background=""
}
content.children[parseInt(Math.random()*content.children.length)].style.background="rgb(146, 11, 230)"
}
</script>
</html>
随机点名