9宫格抽奖1

在之前我的flex九宫格布局基础上,来一个简单的抽奖界面,代码如下:
html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <style>
        .lottery-draw-container{
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
            width: 300px;
            height: 300px;
            border: 1px solid #000;
            display: flex;
            flex-direction: column;
        }
        .item{
            flex-basis: 100px;
            display: flex;
            justify-content:center;
            align-items: center;
            border: 1px solid #000;
        }
        .active{
            background-color: red;
        }
    style>
head>
<body>
<div class="lottery-draw-container">
    <div style="display: flex;flex:1;">
        <div class="item active"><span>一等奖span>div>
        <div class="item"><span>二等奖span>div>
        <div class="item"><span>三等奖span>div>
    div>
    <div style="display: flex;flex:1;">
        <div class="item"><span>四等奖span>div>
        <span class="item"><span>开始span>span>
        <div class="item"><span>五等奖span>div>
    div>
    <div style="display: flex;flex:1;">
        <div class="item"><span>六等奖span>div>
        <div class="item"><span>七等奖span>div>
        <div class="item"><span>八等奖span>div>
    div>
div>

<script>
    let items = document.querySelectorAll("div.item");
    let itemsLen = items.length;
    let startBtn = document.querySelector("span.item");

    let timer = null;

    function start(){
        let randomNum = Math.floor(Math.random()*itemsLen)+20;//20表示变换次数,随意
        let curVal = 0;//当前值默认从一等奖开始
        clearInterval(timer);//用定时器时要清除定时器,不然会出问题
        timer = setInterval(function(){
            for(let i=0;i<itemsLen;i++){
                items[i].classList.remove("active");
            }
            curVal ++;
            items[curVal%itemsLen].classList.add("active");
            if(curVal == randomNum){//在这里可以进行抽奖结果处理
                clearInterval(timer);
            }
        },100)
    }

    startBtn.onclick = function () {
        start();
    }
script>
body>
html>
这段代码还有许多不足之处,如变换速度没有变化,之后会进一步改进

你可能感兴趣的:(9宫格抽奖1)