————定義兩個數組,一個裝姓名,一個裝事件,順便定義一個定時器名 //document.getElementById("sb").innerHTML 獲取到的ID名為sb的元素裡面的內容//Math.floor(Math.random()*sname.length) 隨機生成一個0到sname.l ...
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 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="開始" onclick="boxone()" /> 48 <div class="box3" id="sth"></div> 49 <input type="button" value="結束" onclick="boxtwo()" /> 50 </div> 51 <script type="text/javascript">
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 </script> 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); }