<div class="box"> <div class="div2">短裙</div> <div class="div3">口红</div> <div class="div4">草莓</div> <div class="div5">西瓜</div> <div class="div6">奶茶</div> <div class="div7">美甲</div> <div class="div8">谢谢参与</div> <div class="div9">苹果13</div> <strong class="button"> 点击抽奖</strong> </div>
* { margin: 0; padding: 0; } .box { width: 340px; height: 340px; border: 1px #00FFFF solid; position: relative; margin: 100px; } .box div { width: 100px; height: 100px; background-color: royalblue; text-align: center; line-height: 100px; } .div2 { position: absolute; top: 10px; left: 10px; } .div3 { position: absolute; top: 10px; left: 120px; } .div4 { position: absolute; top: 10px; left: 230px; } .div5 { position: absolute; top: 120px; left: 230px; } .div6 { position: absolute; top: 230px; left: 230px; } .div7 { position: absolute; top: 230px; left: 120px; } .div8 { position: absolute; top: 230px; left: 10px; } .div9 { position: absolute; top: 120px; left: 10px; } .button { width: 100px; height: 100px; background-color: #62c6a3; position: absolute; text-align: center; line-height: 100px; top: 120px; left: 120px; }
let button = document.getElementsByClassName('button')[0]; let box = document.getElementsByClassName('box')[0]; let pirze = box.getElementsByTagName('div'); let k = 0; let time = 500; let count = 0; let int; let rom = 0; button.onclick = eve; function eve() { pirze[k].style.background = "pink"; int = setInterval(pu, time) rom = Math.floor(Math.random() * pirze.length); button.onclick = null; } function pu() { if (k < pirze.length - 1) { k++; pirze[k - 1].style.background = "royalblue"; pirze[k].style.background = "pink"; } else { k = 0; count++; pirze[pirze.length - 1].style.background = "royalblue"; pirze[k].style.background = "pink"; } if (count <= 5) { if (time <= 100) { time = 100; } else { time -= 20; } } else { if (time >= 500) { time = 500; } else { time += 20; } } if (count > 7 && rom == k) { clearInterval(int); count = 0; rom = 0; time = 500; button.onclick = eve; let text = pirze[k].innerHTML; setTimeout(function(){ alert("恭喜您获得:" + text); },300) }else{ clearInterval(int); int = setInterval(pu, time) } }
1. 获取按钮标签,并给它绑定点击事件,点击执行 eve 函数作为事件函数
2. 创建全局变量 k 初始为 0 ,表示为当前选中奖品的下标
3. 获取奖品列表,当点击后,先让第一个奖品修改背景颜色为粉色,也就是 k 下标对应的奖品
4. 创建全局变量 time 初始为 500 ,在点击事件函数内创建定时器,每隔 time 毫秒,执行 pu 函数
5. 获取奖品列表,并创建 pu 函数,在函数内判断 k 是否小于 7 (奖品的数量 - 1)
6. 如果小于7,执行 k++ 表示让当前选中的下标加一,让上一个奖品也就是 k - 1 下标对应的奖品颜色为蓝色
7. 并让当前选中的奖品也就是 k 下标对应的奖品背景颜色为粉色
8. 如果不小于7,表示 k 不能再自增了,需要重新初始为 0 ,