<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #wrap{ text-align: center; width:500px; margin: 100px auto; position: relative; } #ul1{ width: 303px; height: 303px; margin: 50px auto; padding:0; border-top:1px solid black; border-left: 1px solid black; } #ul1 li{ float: left; border-right: 1px solid black; border-bottom: 1px solid black; list-style: none; width: 100px; height: 100px; line-height: 100px; text-align: center; } #tooltips{ width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); position: absolute; top: 0; z-index: 999; display: none; } #info{ width: 400px; height: 200px; background-color: white; margin: 150px auto; } #info .title{ width: 100%; height: 40px; background-color: #009f95; line-height: 40px; color: white; padding-left: 20px; box-sizing: border-box; } #info .btn button{ background-color: #009f95; color: white; outline: none; font-size: 10px; width:60px; height: 30px; margin-left: 300px; } #info .content { height: 120px; padding: 20px; box-sizing: border-box; } </style> </head> <body> <div id="wrap"> <button id="btn">開始抽獎</button> <ul id="ul1"> <li>鼠標</li> <li>1000萬</li> <li>100優惠卷</li> <li>很遺憾</li> <li>鍵盤</li> <li>iphoneX</li> <li>很遺憾</li> <li>迪拜10日遊</li> <li>很遺憾</li> </ul> </div> <!-- 提示信息 --> <div id="tooltips"> <div id="info"> <div class="title">信息</div> <div class="content">恭喜你,中獎了</div> <div class="btn"> <button id="confirm">肯定</button> </div> </div> </div> <script type="text/javascript"> //思路: 1 實現紅色背景切換 2 當運動中止,彈出對話框--用js去修改tooltips的display 變爲block var oStart = document.getElementById("btn") var aLi = document.getElementsByTagName("li") //提示框 var oTooltips = document.getElementById("tooltips") //肯定按鈕 var oConfirm = document.getElementById("confirm") //當前li的下標 var nowIndex = 0 // setInterval的id var timer = null oStart.onclick = function(){ //生成一箇中獎數字 var randomInt = getRandomInt(0, 8) console.log(randomInt) //下面的代碼只是爲了給用戶一個感受:正在抽獎 timer = setInterval(function(){ for(var i = 0; i< aLi.length; i++){ aLi[i].style.backgroundColor = "white" } aLi[nowIndex].style.backgroundColor = "red" nowIndex++ //randomInt表示中獎的數字,若是nowIndex和randomInt同樣,咱們就認爲當前的li是抽中的獎品 if(nowIndex === randomInt){ clearInterval(timer) oTooltips.style.display = "block" } // nowIndex = nowIndex % aLi.length nowIndex %= aLi.length }, 500) //思考一個問題:何時中止?當中獎的時候中止, 抽中的是誰? //能夠用隨機數生成一個具體中獎的數字 randomInt } //當點擊肯定的時候,提示框消失 oConfirm.onclick = function(){ //讓tooltips消失 oTooltips.style.display = "none" } function getRandomInt(min, max){ return Math.floor(Math.random()*(max - min + 1) + min) } </script> </body> </html>