话不多说,直接上代码↓
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>九宫格抽奖</title> <!-- 初始化 --> <style> * { margin: 0; padding: 0; } /* 添加css样式 */ .box { width: 340px; height: 340px; position: relative; margin: 100px; } .box div { width: 100px; height: 100px; background-color: aqua; 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; rot: 1 } .div8 { position: absolute; top: 230px; left: 10px; rot: 95 } .div9 { position: absolute; top: 120px; left: 10px; } .button { width: 100px; height: 100px; background-color: yellow; position: absolute; text-align: center; line-height: 100px; top: 120px; left: 120px; } </style> </head> <body> <!-- 在HTML中用div标签包每个"奖品"并命不同css名,(命不同的css名称,用于给不同的奖品定位到合适位置),再用b标签包"抽奖"按钮(命名为"button"再加上点击事件命名"eve()",最后将所有内容都包在一个大div中(命名为"box) --> <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">爱疯14</div> <div class="div9">再来一次</div> <strong class="button" οnclick="eve()"> 点击抽奖</strong> </div> <script> let button = document.getElementsByClassName('button')[0]; let box = document.getElementsByClassName('box')[0]; let div = box.getElementsByTagName('div'); let k = 0; let time = 100; let count = 0; let int; let rom = 0; function eve() { div[k].style.background = "pink"; int = setInterval(pu, time) rom = Math.floor(Math.random() * div.length); button.onclick = null; } function pu() { if (k < div.length - 1) { k++; div[k - 1].style.background = " aqua"; div[k].style.background = "pink"; } else { k = 0; div[div.length - 1].style.background = " aqua"; div[k].style.background = "pink"; count++; } if (count > 11 && rom == k) { clearInterval(int); time = 100; button.onclick = eve; let text = div[k].innerHTML; setTimeout(function() { alert("恭喜您获得:" + text); }, 100) } else { clearInterval(int); int = setInterval(pu, time) } } </script> </body> </html>