利用随机数与定时器做一个简简单单的九宫格抽奖;
html部分:
<div class="box"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div> <div class="div4">4</div> <div class="div5">5</div> <div class="div6">6</div> <div class="div7">7</div> <div class="div8">8</div> <strong class="button">点击抽奖</strong> </div>
js部分:
let button = document.getElementsByClassName('button')[0]; let k = 0; let box = document.getElementsByClassName('box')[0]; let prize = box.getElementsByTagName("div"); let time = 100; let int; let num = 0; let count = 0; let rom = 0; //添加点击事件 button.onclick = function(){ prize[k].style.backgroundColor = "red"; rom = Math.floor(Math.random() * prize.length); //计时器 int = setInterval(scrolls,time); } // function scrolls(){ if(k < prize.length - 1){ k++; prize[k-1].style.backgroundColor = "aqua"; prize[k].style.backgroundColor = "red"; }else{ k = 0; prize[prize.length - 1].style.backgroundColor = "aqua"; prize[k].style.backgroundColor = "red"; } //当圈数小于等于五时 if(count <= 2){ //时间,速度 if(time <= 100){ time = 200; }else{ time -= 0; } }else{ if(time >= 500){ time = 400; }else{ time += 20; } } if(num == 4){ num = 0; count++; }else{ num++; } //定时器 if(count > 8 && rom == num){ clearInterval(int); }else{ clearInterval(int); int = setInterval(scrolls,time); } }
css部分各位可以凭借自己随机发挥;
*{ margin: 0; padding: 0; } .box{ width: 340px; height: 340px; border: 1px pink solid; position: relative; margin: 100px; } .box div{ width: 100px; height: 100px; background-color: aqua; text-align: center; line-height: 100px; } .div1{ position: absolute; top: 10px; left: 10px; } .div2{ position: absolute; top: 10px; left: 120px; } .div3{ position: absolute; top: 10px; left: 230px; } .div4{ position: absolute; top: 120px; left: 230px; } .div5{ position: absolute; top: 230px; left: 230px; } .div6{ position: absolute; top: 230px; left: 120px; } .div7{ position: absolute; top: 230px; left: 10px; } .div8{ position: absolute; top: 120px; left: 10px; } .button{ width: 100px; height: 100px; background-color: pink; text-align: center; line-height: 100px; position: absolute; top: 120px; left: 120px; }
主要就是设置定时器来控制转速,通过生成随机数来控值转的圈数及在第几格停留