javascript实现随机抽奖,供大家参考,具体内容如下
首先创建一个数组用于存放抽奖的参与者:
var arr=[\'张三\',\'波波\',\'kk\',\'莉莉\',\'张三丰\',\'刘德华\',\'周杰困\',\'你那儿\',\'zhere\',\'好的\'];
给开始和结束按钮div添加点击事件:
//添加点击开始则开始循环播放 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实现循环事件,每隔100毫秒就执行一次循环,随机得到存放参与者的数组的长度之间的随机数,不断修改innerText实现用户滚动效果:
//循环事件 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); } //循环播放列表 function show(){ thisone=getindex(); document.getElementById(\"show\").innerText=arr[thisone]; i=setTimeout(\"show()\",100); }
实现的最终效果图如下:
当点击开始时:
当点击暂停时:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
© 版权声明
THE END
暂无评论内容