温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript如何实现随机点名程序

发布时间:2021-04-12 09:40:44 来源:亿速云 阅读:181 作者:小新 栏目:web开发

这篇文章给大家分享的是有关JavaScript如何实现随机点名程序的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

具体内容如下

效果:

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 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: 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 id="box">
  <div id="stuName">
   随机名单
  </div>
  <input id="btn" type="button" value="开 始" onclick="goAndStop()">
 </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>

感谢各位的阅读!关于“JavaScript如何实现随机点名程序”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI