抽奖

效果:点击开始,随机抽奖,点击结束就停止。


head部分:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #open{
            height:30px;
            width:100px;
            background:red;
            color:white;
            text-align:center;
            line-height:30px;
            font-size:20px;
            float:left;
            margin-right:10px;
        }
        #close{
            float:left;
            height:30px;
            width:100px;
            background:red;
            color:white;
            text-align:center;
            line-height:30px;
            font-size:20px;
        }
        .all{
            height:600px;
            width:600px;
            border:1px solid #000;
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;

        }
        .all>div{
            height:140px;
            width:140px;
            background:greenyellow;
            text-align:center;
            line-height:140px;
            color:white;
            font-size:50px;
        }
    </style>
</head>
body部分:
<body>
<div id="open">开始游戏</div>
<div id="close">结束</div>
<div class="all" id="all">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
    <div>9</div>
    <div>10</div>
    <div>11</div>
    <div>12</div>
    <div>13</div>
    <div>14</div>
    <div>15</div>
    <div>16</div>
</div>
js部分:
<script>
    window.onload=function(){
        var oOpen=document.getElementById("open");
        var oClose=document.getElementById("close");
        var oAll=document.getElementById("all");
        var aAll=oAll.getElementsByTagName("div");
        var onOff=true; 
// 声明个开关,让它为真
        oOpen.onclick=function(){
            if(onOff){
                // 加个判断,让开关为假时,进入for循环
                onOff=false;
                timer=setInterval(function(){
                    var random=Math.floor(Math.random()*16);
                    for(var i=0;i<aAll.length;i++){
                        aAll[i].style.background="greenyellow";
                    }
                    aAll[random].style.background="#000";
                },50);
            }
        }

        oClose.onclick=function(){
            onOff=true;
            // 如上所述,但它开始和结束都点击一次后,无法进行第二次,需要刷新,所以加个开关让它为真,
            // 就可以结束后回到上面重新进行循环
            clearInterval(timer);
        }
    }
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/xinye666666/article/details/80696836