该段代码是从固定位置开始,也可以利用生成随机数从任意位置开始,也可以通过点击触发请求由后端传输数据决定停止时间
<!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> <!-- <link rel="stylesheet" href="./static/aaa.css"> --> <style> *{margin:0px;padding:0px;} ol,li{list-style:none;} .box{600px;margin:200px auto;background:peachpuff;} .box li{180px;line-height: 50px;font-size:20px;margin:4px 4px;float:left;background:papayawhip;text-align: center;border-radius:20px;color:#fff;} .box li.active{background:paleturquoise;} .box li.start{background:#e6162e;} </style> </head> <body> <div class="box"> <ul> <li class="prize prize-1">奖品一</li> <li class="prize prize-2">奖品二</li> <li class="prize prize-3">奖品三</li> <li class="prize prize-8">谢谢参与</li> <li class="start">开始抽奖</li> <li class="prize prize-4">奖品四</li> <li class="prize prize-7">奖品七</li> <li class="prize prize-6">奖品六</li> <li class="prize prize-5">奖品五</li> </ul> </div> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(function () { var speed = 100; var now = 1 var end = 5 $('.start').click(function () { time() change() }) function change() { $('.prize').removeClass('active') $('.prize-' + now).addClass('active') now++; if (now > 9) { now = 1 } else { return false } } var a; function time() { a = setTimeout(function () { change() time() }, speed) setTimeout(function () { if (now == end) { clearTimeout(a) } }, 3000) } }) </script> </body> </html>