时间:2021-08-04 08:33:51 | 栏目:JavaScript代码 | 点击:次
用JS实现一个随机点名系统,供大家参考,具体内容如下
每次上课前10分钟,老师都会叫我们回答问题,奈何每次都是点学号,好像每次我都能中奖,我直接跟老师提议,老师,我用来JS来帮你写个随机点名的系统吧!这样就不会每次都抽到我了,哈哈
先看效果:
代码如下:
<!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> </head> <body> <button id="box1">开始</button> <button id="box2">结束</button> <span id="box">Tom</span> <script> //获取页面中的元素 var btn1 = document.getElementById('box1'); var btn2 = document.getElementById('box2'); var span = document.getElementById('box'); var names = ['Tom', 'Jack', 'Lucy', 'Peter', 'Mark', 'Min', 'Liu', 'Rani']; var timer; btn1.onclick = function() { window.clearInterval(timer); timer = window.setInterval(countName, 100); }; btn2.onclick = function() { window.clearInterval(timer); }; function countName() { var index = parseInt(Math.random() * names.length); span.innerHTML = names[index]; } </script> </body> </html>