上课时候突发奇想,想着做一个抽奖系统出来,于是用了两小时去写了这个案例,主要用了随机值函数,其他没什么特别地方,代码自我感觉还算规范。

在线地址:https://ebuxsf.coding.io/dinner

主要代码:

<h1>今晚吃什么?</h1>
<div class="btn">开始</div>

<div class="boxs"></div>

<div class="alert">今晚<span class="text"></span></div>
<div class="mask"></div>
<script>

window.onload = dosInner()

var timerNum = 3 //秒数初始化变量

function dosInner() {
    var dosin = ["关东煮", "沙县小吃", "学校食堂", "云吞", "吃鸡", "外卖", "泡面", "吃屎", "关东煮", "沙县小吃", "学校食堂", "云吞", "吃鸡", "外卖", "泡面", "吃屎", "关东煮", "沙县小吃", "学校食堂", "云吞", "吃鸡", "外卖", "泡面", "吃屎"]
    var dosinHtml = ''
    var length = dosin.length
    for (var i = 0; i < length; i++) {
        dosinHtml += "<div class='box'>" + dosin[i] + "</div>"
    }
    document.querySelector('.boxs').innerHTML = dosinHtml

    document.querySelector('.btn').onclick = function () {
        runSelect(length)
    }
}

var num = 0;

function runSelect(length) {
    document.querySelector('.btn').style.opacity = '0'

    var times = setInterval(function () {
        num++
        console.log(num)

        if (num == timerNum) {
            clearInterval(times)
            setTimeout(function () {
                show()
            }, 300)
        }
    }, 1000)

    var length = length - 1
    var boxtimes = setInterval(function () {
        var mathNum = Math.ceil(Math.random() * length)
        var obox = document.getElementsByClassName('box')[mathNum]
        // console.log(obox, mathNum)

        document.querySelector('.text').innerHTML = obox.innerText

        obox.classList.add('red')
        setTimeout(function () {
            obox.classList.remove('red')
        }, 300)

        if (num == timerNum) {
            clearInterval(boxtimes)
        }
    }, 100)

    if (num == timerNum) {
        num = 0;
    }
}

function show() {
    document.querySelector('.alert').style.display = 'block'
    document.querySelector('.mask').style.display = 'block'
    setTimeout(function () {
        document.querySelector('.alert').style.display = 'none'
        document.querySelector('.mask').style.display = 'none'
    }, 1500)
    document.querySelector('.btn').style.opacity = '1'

}
</script>