JavaScript实现随机点名程序

录制的gif效果图没那么理想,其实速度是比这个快的

思路:

1.定义一个数组,存放名单
2.启动定时器,设定间隔时间不断调用函数
3.Math.random()获取随机下标,根据下标的随机变换取出数组中对应的元素
4.逻辑代码完成后,通过DOM对象把变化的结果呈现在页面上

JS代码:

<script> var arr = ["唐僧", "孙悟空", "猪八戒", "沙悟净", "白骨精", "玉皇大帝", "红孩儿", "白骨精", "太上老君"] var myTimer = null //定时器编号 // 既是启动定时器的函数,也是停止定时器的函数 function goAndStop(){ // 如果当前没有定时器在执行,则启动,否则,停止定时器; if(myTimer == null){ // 启动定时器,随机下标,取出名字 myTimer = setInterval(function(){ // 1、随机下标 var index = parseInt(Math.random()*arr.length) // 2、根据下标取出学生的姓名,显示在页面上 document.getElementById("stuName").innerHTML = arr[index] },10); //启动定时器的同时,改变按钮状态,为下次单击做准备 document.getElementById("btn").value = "停 止" }else{ // 当前若有有定时器在执行,则停止定时器, 恢复初始状态 window.clearInterval(myTimer) myTimer = null document.getElementById("btn").value = "开 始" } } </script>

HTML + CSS + JS 源码:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta 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: 300px; margin: 100px auto; } #stuName{ width: 100%; height: 80px; border: 2px solid gray; line-height: 80px; text-align: center; font-size: 30px; color:orange; font-weight: bold; } input{ margin-top:30px; width: 100%; height: 50px; font-size: 20px; font-weight: bold; } </style> </head> <body> <div> <div> 随机名单 </div> <input type="button" value="开 始"> </div> </body> </html> <script> var arr = ["唐僧", "孙悟空", "猪八戒", "沙悟净", "白骨精", "玉皇大帝", "红孩儿", "白骨精", "太上老君"] var myTimer = null function goAndStop(){ if(myTimer == null){ myTimer = setInterval(function(){ var index = parseInt(Math.random()*arr.length) document.getElementById("stuName").innerHTML = arr[index] },10); document.getElementById("btn").value = "停 止" }else{ window.clearInterval(myTimer) myTimer = null document.getElementById("btn").value = "开 始" } } </script>

这是我的一些思路,分享给大家!

如果你有更好的方法,欢迎下方留言相互交流!

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/f110810b3b65d33bb5aa9449fbd889f6.html