一个简单的抽奖程序
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>抽奖程序</title> 6 <script type="text/javascript" src="http://common.cnblogs.com/script/jquery.js"></script> 7 <script> 8 $(function () { 9 var time, 10 i, 11 idx="01247653", 12 items=$('.test1'), 13 num=items.length, 14 gameOver=true; 15 16 $('#start').click(function(){ 17 if(gameOver){ 18 gameOver=false; 19 time=Math.random()*20; 20 i=7; 21 setTimeout(loop,time); 22 } 23 }); 24 25 function loop(){ 26 items.removeClass('active'); 27 items.eq(idx.charAt(i%num)).addClass('active'); 28 i++; 29 if(time<500){//设置阈值 30 //时间越长,执行越慢,达到一个缓慢的效果 31 //Math.random()*(n-m)+m 返回指定范围的随机数(m-n之间)的公式 32 time+= parseInt(Math.random()*(20-10)+10,10); 33 setTimeout(loop,time); 34 }else{ 35 gameOver=true; 36 alert(items.filter('.active').text()); 37 } 38 } 39 }); 40 </script> 41 </head> 42 <body> 43 <style> 44 .test1,.test2{ 45 width:20px; 46 height:20px; 47 border:1px solid red; 48 display: inline-block; 49 overflow: hidden; 50 } 51 52 .active{ 53 background: red; 54 } 55 </style> 56 <div id="container"> 57 <div class="test1" >1</div> 58 <div class="test1" >2</div> 59 <div class="test1" >3</div> 60 <br/> 61 <div class="test1" >4</div> 62 <div id="start" class="test2">抽</div> 63 <div class="test1" >5</div> 64 <br/> 65 <div class="test1" >6</div> 66 <div class="test1" >7</div> 67 <div class="test1" >8</div> 68 </div> 69 </body> 70 </html>
效果:
参考: