1 <!DOCTYPE html> 2 <html> 3 <head> 4 < charset=\"UTF-8\"> 5 < ></ > 6 <style type=\"text/css\"> 7 *{ 8 margin: 0; 9 padding: 0; 10 } 11 .box1{ 12 width: 700px; 13 height: 600px; 14 background-color: orange; 15 margin: auto; 16 position: relative; 17 } 18 .box2{ 19 width: 200px; 20 height: 200px; 21 background: wheat; 22 position: absolute; 23 left: 50px; 24 top: 150px; 25 font: 30px arial; 26 color: red; 27 line-height: 200px; 28 text-align: center; 29 } 30 .box3{ 31 width: 200px; 32 height: 200px; 33 background: wheat; 34 position: absolute; 35 left: 450px; 36 top: 150px; 37 font: 30px arial; 38 color: red; 39 line-height: 200px; 40 text-align: center; 41 } 42 </style> 43 </head> 44 <body> 45 <div class=\"box1\"> 46 <div class=\"box2\" id=\"sb\"></div> 47 <input type=\"button\" style=\"margin: 500px 210px;\" value=\"开始\" =\"boxone()\" /> 48 <div class=\"box3\" id=\"sth\"></div> 49 <input type=\"button\" value=\"结束\" =\"boxtwo()\" /> 50 </div> 51 < type=\"text/ \">
52 var sname=[\"小黄\",\"小红\",\"小蓝\",\"小绿\",\"小青\",\"小紫\",\"小橙\"]; 53 var sthing=[\"吃瓜\",\"卖萌\",\"嗑瓜子\",\"搬凳子\",\"看戏\",\"卖汽水\"]; 54 var timer; 55 function boxone(){ 56 clearTimeout(timer); 57 document.getElementById(\"sb\").innerHTML= 58 sname[Math.floor(Math.random()*sname.length)]; 59 60 document.getElementById(\"sth\").innerHTML= 61 sthing[Math.floor(Math.random()*sthing.length)]; 62 63 timer=setTimeout(boxone,200); 64 } 65 function boxtwo(){ 66 clearTimeout(timer); 67 } 68 </ > 69 </body> 70 </html>
————
定义两个数组,一个装姓名,一个装事件,顺便定义一个定时器名
var sname=[\"小黄\",\"小红\",\"小蓝\",\"小绿\",\"小青\",\"小紫\",\"小橙\"]; var sthing=[\"吃瓜\",\"卖萌\",\"嗑瓜子\",\"搬凳子\",\"看戏\",\"卖汽水\"]; var timer;
//document.getElementById(\"sb\").innerHTML 获取到的ID名为sb的元素里面的内容
//Math.floor(Math.random()*sname.length) 随机生成一个0到sname.length(两个边界均不包含)之间的数并向下取整,以此来随机生成一个数组sname的下标。
此段代码意为在数组sname中随机找一个元素将其赋给ID名为sb的元素
document.getElementById(\"sb\").innerHTML=
sname[Math.floor(Math.random()*sname.length)];
————
利用定时器每200ms调用一次函数,为了使滚动速度不会越来越快,每使用定时器调用一次函数,都需要清除上一个定时器
function boxone(){ clearTimeout(timer); document.getElementById(\"sb\").innerHTML= sname[Math.floor(Math.random()*sname.length)]; document.getElementById(\"sth\").innerHTML= sthing[Math.floor(Math.random()*sthing.length)]; timer=setTimeout(boxone,200); }
————
这里结束按钮的方法,清除定时器就行了
function boxtwo(){ clearTimeout(timer); }
继续阅读与本文标签相同的文章
上一篇 :
数据类型和运算符
-
DBengine 排名第一,云数据库 InfluxDB 版正式商业化!
2026-05-19栏目: 教程
-
阿里有个超神秘的组织,CEO们来了都要翻牌 | 开发者必读(056期)
2026-05-19栏目: 教程
-
云原生计算重塑企业IT架构 - 分布式应用架构
2026-05-19栏目: 教程
-
阿里云创新大会再出发,一些变化即将发生
2026-05-19栏目: 教程
-
阿里云的包年包月、按量付费、抢占式实例计费方式是什么,如何选择
2026-05-19栏目: 教程
