20240309web前端_第四次作业_完成随机点名程序

时间:2024-04-25 10:40:56

要求

一、结合抽奖案例完成随机点名程序,要求如下:
1.点击点名按钮,名字界面随机显示,按钮文字由点名变为停止
2.再次点击点名按钮,显示当前被点名学生姓名,按钮文字由停止变为点名
3.样式请参考css及html*发挥完成。

代码

 
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>随机点名</title>
<style>
*{
 margin-left: 0px;
 margin-top: 0px;
 }
.container{
 width: 600px;
 height: 600px;
border: 1px solid yellow;
 position: absolute;
 left: 50%;
 margin-left: -400px;
 text-align: center;
 line-height: 100px;
 
 }
 .box,.box2{
 width: 300px;
 height: 300px;
 background-color: pink;
 margin: auto;/*水平距离的居中*/
 margin-top: 50px;
line-height: 300px;
 }
 .box2{
background-color: aqua;
 }
 #show{
font-size: 30px;
 color: aliceblue;
 font-weight: bold;
} #start{
 width: 300px;
 height: 50px;
 background-color:aquamarine ;
 }
</style>
</head>
<body>
<div class="container">
<div class="box" id="box">
<span id="show">姓名</span>
 </div>
 <button id="start" onclick="change()">点名</button>
 </div>
</body>
</html>
 
<script>
 //标志位
 var flag=false
 var awards=["张三","李四","王五","赵六","钱七","孙八"]
 //2.获取对应dom对象
    var box=document.getElementById("box")
    var show=document.getElementById("show")
    var start=document.getElementById("start")
 
 //3.定义定时器
    var timer
//4.点击事件触发
    function change(){
        if(!flag){
        flag=true
        start.innerHTML="停止点名"
        timer=setInterval(function(){
  // --- 获取匹配姓名数组的索引随机数
        let index = Math.floor(Math.random()*awards.length)
        show.innerHTML=awards[index]
        box.setAttribute("class","box2")
 },10)
 }  else{
        flag=false
        start.innerHTML="开始点名"
        clearInterval(timer)
        box.setAttribute("class","box")
 }
 }
</script>

演示