HTML + CSS+ JavaScript 随机点名案例

402 阅读1分钟

闲来无事 写了一个 点名案例 只需将数组中的需要随机的数据改一下就行 会直接渲染到html 当然你也可以自己修改一下CSS

HTML: 记得引入css js

<div class="ren">
    </div>
    <div class="anniu">
    <button class="open">开始</button>
    <button class="two">讲台</button>
    <button onclick="stop()">结束</button>
    </div>

CSS:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.ren {
    width: 800px;
    margin: 0 auto;
    border: 1px solid red;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}

.ren div {
    width: 80px;
    height: 80px;
    text-align: center;
    line-height: 80px;
    border: 1px solid red;
}

.re {
    border: 1px solid red;
}
.blue {
    background-color: blue;
}
.anniu {
    width: 800px;
    margin: 0 auto;
    border: 1px solid red;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
}
.anniu button {
    justify-content: center;
    align-items: center;
    width: 200px;height: 200px;
}
.anniu .two {
height: 100px;
width: 200px;
line-height: 100px;
}

JS:

var open = document.querySelector('.open')
var divs = document.querySelector('.ren')
var times = null
var arr = [1,2,3,4,5] //数组
var num = Math.floor(Math.random() * arr.length);
for (let i = 0; i < arr.length; i++) { //遍历数组
    var d = document.createElement('div') //创建一个div
    d.innerText=arr[i] //div内容为第数组的第i个 第几次执行就是第几个
    d.setAttribute('class','re')  //添加css类名 类名re
    divs.append(d) //追加进div
}
let divss = document.querySelectorAll('.ren > div') //获取.ren内的所有的div也就是上面创建的div
open.onclick=function dingshi(){ //点击开始执行函数
    times = setInterval(e=>{ //定时器存进 times
        var nums = Math.floor(Math.random() * 36);//随机数
        for(let i = 0; i < arr.length;i++){ //外for 用来设置排他
            divss[i].setAttribute('class','re') //给第i个设置类名 re 这里好像 不让为空所以我随便设置了个
            for(let i = 0; i<=arr.length; i++){ //遍历数组
                divss[nums].setAttribute('class','blue') //给当前随机到的div设置类名 blue
            }
        }
    },100)//每100毫秒执行一次
}
function stop(){
    clearInterval(times) //清除定时器
}