jquery旋转抽奖详解

//style样式
* {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html,
        body {
            width: 100%;
            height: 100%;
        }

        section {
            width: 300px;
            height: 300px;
            display: flex;
            flex-wrap: wrap;
            justify-content: space-around;
            align-items: center;
            margin: 50px auto;
            border: 10px solid goldenrod;
        }

        section>div {
            width: 90px;
            height: 90px;
            text-align: center;
            background-color: yellow;
            line-height: 90px;
            font-size: 12px;
        }

        .red {
            background-color: red;
            color: white;
        }
//html
 <section></section>
//jquery代码
<script src="./jquery/jquery-3.4.1.js"></script>
<script>
    // 将将奖品内容写到数组中
    var items = ['1元现金红包', '30元租车劵', '迪士尼门票', '2日免费用车', '开始抽奖', '电影票', '50元租车券', '定制LED电扇', '100元租车券'];
    layout()
    // 布局
    function layout() {
        // 记录拼接的html字符串
        var html = '';
        for (var i = 0; i < items.length; i++) {
            // 拼接字符串
            var div = `<div>${items[i]}</div>`
            html += div
        }
        // 将html字符串添加到section中
        $('section').html(html)
    }
    // 点击抽奖
    // 记录点击次数
    var count = 0
    $('section>div:eq(4)').click(function () {
        // 判断是否在抽奖 是 点击无效
        if (timer) {
            return
        }
        count += 1
        // 抽奖超过三次不能在抽奖了
        if (count > 3) {
            alert('次数用光了')
            return
        }
        start()
    })

    // 抽奖逻辑

    // timer为null 表示没有抽奖
    // timer有值 表示抽奖
    var timer = null;

    function start() {
        // 记录function调用次数
        var randomCount = 0;
         // 将索引值放到数组里面 然后开始随机索引值
         var num = [0, 1, 2, 5, 8, 7, 6, 3];
          // 随机数
          //让他从那个位置开始旋转
          var random = Math.floor(Math.random() * num.length);
        timer = setInterval(function () {
            randomCount++
            random++
            
           if (random == 8) {
               random = 0
           }
           //取出当前的div的索引值
           var arr = num[random];
           //给元素添加移除class类名
           $('div').eq(arr).addClass('red');
           $('div').eq(arr).siblings().removeClass('red')
            //执行20次的时候结束
            if (randomCount == 20) {
                clearInterval(timer);
                timer = null;
                setTimeout(function () {
                    alert(items[arr])
                }, 0)
            }

        }, 400)
    }
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值