A Pen by jununx

Thumbnail
This awesome code was written by jununx, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright jununx ©
  • HTML
  • CSS
  • JavaScript
    <div class="lottery">
    <ul class="list">
        <li class="item-1 active">1</li>
        <li class="item-2">2</li>
        <li class="item-3">3</li>
        <li class="item-4">4</li>
        <li class="item-5">5</li>
        <li class="item-6">6</li>
        <li class="item-7">7</li>
        <li class="item-8">8</li>
    </ul>
    <button class="btn">抽奖</button>
</div>

/*Downloaded from https://www.codeseek.co/jununx/a-pen-by-jununx-YXyBBN */
    ul { list-style: none; }
.lottery { position: relative; width: 184px; height: 184px; line-height: 58px; text-align: center; overflow: hidden; margin: 0 auto; }
.lottery li, .lottery .btn { position: absolute; width: 60px; height: 60px; border: 1px #ccc solid; z-index: 1; }
.lottery .item-1 { top: 0; left: 0; }
.lottery .item-2 { top: 0; left: 61px; }
.lottery .item-3 { top: 0; left: 122px; }
.lottery .item-4 { top: 61px; left: 122px; }
.lottery .item-5 { top: 122px; left: 122px; }
.lottery .item-6 { top: 122px; left: 61px; }
.lottery .item-7 { top: 122px; left: 0; }
.lottery .item-8 { top: 61px; left: 0; }
.lottery .active { border-color: red; z-index: 2; }
.lottery .btn { width: 62px; height: 62px; top: 61px; left: 61px; background-color: transparent; cursor: pointer; }


/*Downloaded from https://www.codeseek.co/jununx/a-pen-by-jununx-YXyBBN */
    // 假设iEnd是请求获得的奖品结果
var iEnd = -1;

$('.btn').on('click', function(){

    var $this = $(this);

    // 这个setTimeout是假设的请求
    setTimeout(function(){
        iEnd = Math.floor(Math.random() * 8);
        console.log(iEnd);
    }, 3000);

    // 禁用
    $this.attr('disabled', 'disabled');

    draw($('.lottery'), function(){

        // 第一个奖品是0哦~
        alert('您中到了奖品号下标是:'+ iEnd + ',奖品数字是:'+ (iEnd + 1));

        // 恢复按钮
        $this.removeAttr('disabled');
    });

});

// 开始转动
function draw(oMain, fn){
    var timer = null,
        iNow = oMain.find('.active').index(),
        len = oMain.find('li').length,
        circle = 5, // 至少要转几圈
        iSpeed = 300,
        count = 0, // 转了多少次
        iLast = len; // 最后一次转圈圈

        (function run(){

            // 前3个加速
            if(count > 2){ iSpeed = 100; }

            // 后3个减速
            if(iLast < 2){ iSpeed = 300; }

            iNow++;
            count++;

            if(iNow >= len){ iNow = 0; circle--; }
            oMain.find('li').removeClass('active').eq(iNow).addClass('active');

            timer = setTimeout(run, iSpeed);

            // 得到结果
            if(iEnd !== -1 && circle <= 0 && iNow == iEnd){

                // 为了最后一圈减速,再跑一圈
                iLast--;
                if(iLast == 0){
                    clearTimeout(timer);
                    fn();
                }
            }
        })();
}

Comments