js实现简单的随机点名器

时间:2022-09-21 14:08:36

本文实例为大家分享了js实现简单随机点名器的具体代码,供大家参考,具体内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
  .box {
    width: 200px;
    height: 200px;
    line-height: 200px;
    background-color: #ccc;
    font-size: 30px;
    text-align: center;
  }
  </style>
</head>
<body>
  <div class="box">此乃点名器</div>
  <input type="button" value="点名" id="btn">
  <!-- <button id="btn">点名</button> -->
  <script>
    var btn = document.getElementById("btn");
    var box = document.getElementsByClassName("box")[0];
// 3、写一个随机抽名的案例?(点击按钮开启定时器,
// 定时器中去随机抽取人名,把全班的人放在一个数组中,只要想办法获取随机的索引号就可以)
    btn.onclick = function() {
      if(this.value==="点名") {
      function fn() {
      var arr = ["张三","李四","王五","赵六","黑七","白八","紫九","红薯"];
      var index = parseInt(Math.random()*arr.length);
     var n1 = parseInt(Math.random()*255+1);
     var n2 = parseInt(Math.random()*255+1);
     var n3 = parseInt(Math.random()*255+1);
      box.style.background ="rgb("+n1+","+n2+","+n3+")" ;
      box.innerHTML = arr[index];
      }
      this.value = "停止";
      //定时器不加var声明,涉及到作用域问题 
      timer=setInterval(fn,2);
      }else {
        clearInterval(timer);
        this.value = "点名";
      }
      
    }
 
 
 
 
    </script>
</body>
</html>

效果图如下:

js实现简单的随机点名器

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_42190893/article/details/102930113