老是看到相似的九宮格抽獎效果,後來想本身手擼一個試一試吧。
(多多嘗試,萬一成功了呢 github L6zt)jquery
先來總結一下效果,相似與跑馬燈效果,閃動效果先快後慢。
代碼解析以下所示:
代碼git
<div class="gift-container"> <ul> <li> <section class="gift-box active" data-role="0">0</section> <section class="gift-box" data-role="1">1</section> <section class="gift-box" data-role="2">2</section> </li> <li> <section class="gift-box" data-role="7">7</section> <section class="gift-box get-gift-btn" >抽獎</section> <section class="gift-box" data-role="3">3</section> </li> <li> <section class="gift-box" data-role="6">6</section> <section class="gift-box" data-role="5">5</section> <section class="gift-box" data-role="4">4</section> </li> </ul> <div> <label for="gift-num"> <span>抽獎數字<small>0-7</small>:</span> <input type="text" id="gift-num" name="gift-name"> </label> </div> </div> <script src="jquery.js"></script> <script> $(function () { // 獎號dom元素 let $frameList = $('[data-role]'); let $input = $('#gift-num'); // 定時器的值 let k = null; // 獎號dom元素 總長度 let len = null; // 初始化 閃動間隔時間 毫秒數 let initDelayTime = 50; // 抽獎號數 let times = 0; // 抽圈數 let circleCount = 0; // 是否是在抽獎 let isBusy = false; // 抽獎初始 號數 let oldTimes = null; // 抽獎號數 dom元素 作個排序, 分個大小 frameList = Array.from($frameList).sort((a, b) => { return $(a).data('role') - $(b).data('role') }); len = frameList.length; // 抽獎開始效果 function startGiftAm () { // 抽獎第一幀時,給oldTimes 賦值起始抽號數 k || (oldTimes = times); // 當前應激活的元素 let $curItem = $(frameList[(times++) % len]); //抽獎圈數 circleCount = parseInt((times - oldTimes) / len); // 根據圈數 改變 閃動間隔時間 switch (circleCount) { case 0: case 1: { break; } case 2: case 3: { initDelayTime = 100; break; } default : { initDelayTime = 200 } } // $frameList.removeClass('active'); $curItem.addClass('active'); // 若是夠四圈 而且 當前抽獎號數等於 結束抽獎號數 終止抽獎, 並初始化抽獎 狀態 if(circleCount === 4 && $input.val() == $curItem.data('role')) { circleCount = 0; k = null; isBusy = false; initDelayTime = 50; } else { k = setTimeout(startGiftAm, initDelayTime); } }; // $('.get-gift-btn').on('click', function () { if (!isBusy) { console.log(isBusy); isBusy = true; startGiftAm(); } }) }) </script>
demo地址github