javascript實(shí)現(xiàn)隨機(jī)抽獎(jiǎng)功能
javascript實(shí)現(xiàn)隨機(jī)抽獎(jiǎng),供大家參考,具體內(nèi)容如下
首先創(chuàng)建一個(gè)數(shù)組用于存放抽獎(jiǎng)的參與者:
var arr=['張三','波波','kk','莉莉','張三豐','劉德華','周杰困','你那兒','zhere','好的'];
給開始和結(jié)束按鈕div添加點(diǎn)擊事件:
//添加點(diǎn)擊開始則開始循環(huán)播放
document.getElementById("start").addEventListener("click",va);
//點(diǎn)擊停止則停止播放并顯示恭喜中獎(jiǎng)
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實(shí)現(xiàn)循環(huán)事件,每隔100毫秒就執(zhí)行一次循環(huán),隨機(jī)得到存放參與者的數(shù)組的長(zhǎng)度之間的隨機(jī)數(shù),不斷修改innerText實(shí)現(xiàn)用戶滾動(dòng)效果:
//循環(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);
}
//獲得當(dāng)前名字下標(biāo)
function getindex() {
return parseInt(Math.random()*arr.length);
}
//循環(huán)播放列表
function show(){
thisone=getindex();
document.getElementById("show").innerText=arr[thisone];
i=setTimeout("show()",100);
}
實(shí)現(xiàn)的最終效果圖如下:
當(dāng)點(diǎn)擊開始時(shí):

當(dāng)點(diǎn)擊暫停時(shí):

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript函數(shù)式編程(Functional Programming)組合函數(shù)(Composition)用法分析
JavaScript 以對(duì)象為索引的關(guān)聯(lián)數(shù)組
layui-table獲得當(dāng)前行的上/下一行數(shù)據(jù)的例子
javascript函數(shù)自動(dòng)執(zhí)行常用方法匯總
JS控制靜態(tài)頁(yè)面之間傳遞參數(shù)獲取參數(shù)并應(yīng)用的簡(jiǎn)單實(shí)例

