大家在很多活動頁面上都看到絢麗多彩的抽獎運用,網上也有比較多關於這方面的js和用as。今天我在工作的時候也要做個抽獎的運用。我之前沒有寫過這類的js,也不會as,就得屁顛屁顛的問度娘啦,雖然找到有js寫的也有用框架做的,研究了下,覺得忒復雜。突然想到之前公司有個簡單實現的抽獎js。就要拿過來看看,結合自己的需求封裝成一個類。
html代碼如下:
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> ul{list-style:none;} li{display:inline-block; border:1px solid #000;} span{display:inline-block; padding:10px 15px;} li .lottery_yeah{background:red;} </style> <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.1.min.js"></script> </head> <body> <input type="button" id="btn" value="button" /> <ul id="la" class="lottery_all"> <li><span eid="0" class="lottery_box">1</span></li> <li><span eid="1" class="lottery_box">2</span></li> <li><span eid="2" class="lottery_box">3</span></li> <li><span eid="3" class="lottery_box">4</span></li> <li><span eid="4" class="lottery_box">5</span></li> <li><span eid="5" class="lottery_box">6</span></li> <li><span eid="6" class="lottery_box">7</span></li> <li><span eid="7" class="lottery_box">8</span></li> <li><span eid="8" class="lottery_box">9</span></li> </ul> <script type="text/javascript" src="cj.js"></script> </body> </html>
js代碼如下:
/* * 抽獎封裝對象 * @class LuckyDraw * @param { Number } 抽獎懸停號碼 * @method LuckyDraw.tigerMac * @param { Number, Function } 運動步伐間距,回調函數 * */ function LuckyDraw( numId ) { if ( this instanceof LuckyDraw ) { this.rewardId = numId; this.timer = null; } else { return new LuckyDraw( numId ); } } LuckyDraw.prototype.tigerMac = function( iStep, callback ) { var speed = 200 / iStep, // 時間間隔 $luckyItem = $('#la .lottery_box'), len = $luckyItem.length, index = 0, // 索引值 _this = this; $luckyItem.removeClass('lottery_yeah').eq( index ).addClass('lottery_yeah'); this.timer = setInterval(function () { if ( index + 1 > len ) { index = 0; iStep++; clearInterval( _this.timer ); _this.tigerMac( iStep, callback ); } else { if ( iStep >= 6 ) { if ( _this.rewardId && $luckyItem.eq( index ).attr('eid') == _this.rewardId ) { $luckyItem.eq( index ).addClass('lottery_yeah'); clearInterval( _this.timer ); if ( callback && typeof callback === 'function' ) { callback.call( $luckyItem[index] ); } return } } index++; } $luckyItem.removeClass('lottery_yeah').eq(index).addClass('lottery_yeah'); }, speed) }; // 抽獎 $('#btn').click( (function(){ var n = 3, aLuckyNum = [2, 5, 8], oCj = null; return function() { if ( n ) { oCj = new LuckyDraw( aLuckyNum[n - 1] ); n--; oCj.tigerMac( 1, function(){ if ( Number( $(this).text() ) === 6 ) { alert('恭喜中獎啦!你還有' + n + '次抽獎機會哦!'); } else if ( n ) { alert('^ @ ^ 沒中獎,加油!你還有' + n + '次抽獎機會哦!'); } else { alert('^ @ ^ 沒中獎!謝謝參與'); } } ); oCj = null; }else { alert('你沒有抽獎機會啦'); } } })() );
以上就是整個js抽獎的代碼,至於抽獎布局的話,大家就看着處理吧。大家看到有更好的實現方法,歡迎留言或者聯系我,一起學習!