javascript實現(xiàn)隨機抽獎功能
javascript實現(xiàn)隨機抽獎,供大家參考,具體內(nèi)容如下
首先創(chuàng)建一個數(shù)組用于存放抽獎的參與者:
var arr=[’張三’,’波波’,’kk’,’莉莉’,’張三豐’,’劉德華’,’周杰困’,’你那兒’,’zhere’,’好的’];
給開始和結(jié)束按鈕div添加點擊事件:
//添加點擊開始則開始循環(huán)播放document.getElementById('start').addEventListener('click',va);//點擊停止則停止播放并顯示恭喜中獎document.getElementById('end').addEventListener('click',function (){ count++; clearTimeout(i); var name=arr[thisone]; arr.splice(thisone,1); var get=document.getElementById('get'); get.innerHTML=get.innerHTML+’<br>’; get.innerText=get.innerText+`${count}. `+name;})
用setTimeout實現(xiàn)循環(huán)事件,每隔100毫秒就執(zhí)行一次循環(huán),隨機得到存放參與者的數(shù)組的長度之間的隨機數(shù),不斷修改innerText實現(xiàn)用戶滾動效果:
//循環(huán)事件function va(){ let num=arr.length; console.log(num); if(num===0){ clearTimeout(i); //移除開始事件 document.getElementById('start').removeEventListener('click',va); document.getElementById('show').innerText='沒有了'; return; } setTimeout('show()',100);}//獲得當前名字下標function getindex() { return parseInt(Math.random()*arr.length);}//循環(huán)播放列表function show(){ thisone=getindex(); document.getElementById('show').innerText=arr[thisone]; i=setTimeout('show()',100);}
實現(xiàn)的最終效果圖如下:
當點擊開始時:
當點擊暫停時:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
