原生实现随机点名

    技术2026-08-28  5

    原生实现随机点名

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #name_box li { margin: 10px; padding: 10px; border: 1px solid white; border-radius: 10px; } .active { background-color: white; color: black; /* 2D转换的属性名 */ transform: scale(1.3); /* 过渡效果的属性名 */ transition: transform 0.3s; /* 位移,属于transform的属性值 */ /* translate */ } </style> </head> <body style="background-color: black; color: white;"> <div style="display: flex; flex-flow: column; align-items: center;"> <div>总人数:<span id="total">?</span> 人,抽取: <input type="text" id="size"></div> <div> <button id="btn" type="button" style="height: 50px; font-size: 20px; margin-top: 10px;">点击随机抽取 ?</button> </div> <div> <ul id="name_box" style="list-style: none; margin: 0; padding: 0; display: flex; flex-flow: row wrap;"> </ul> </div> </div> <script> (() => { const btn = document.querySelector('#btn') const name_box = document.querySelector('#name_box') const sizeInput = document.querySelector('#size') const total = document.querySelector('#total') console.log(); let size = sizeInput.value ? parseInt(sizeInput.value) : 1; btn.innerHTML = `点击随机抽取 ${size} 位` const students = [ '张三', '李四', '王五', '阿福', '旺财', '小米', '小红', '白白', '小天', '赵六', '晓晴', '吴浩', '阿勇', '王武', '江山', '天下', '阮天', '萌萌', '芒果', '卿苑', '青柠', '青鸢', '苹芃', '小妮', '子依', '点点', '贤贤', '软甜', '温柔', '御姐', '萝莉', '嘻嘻', '瞅瞅', '精灵', '鲁班', '小智', '月月', '软软', '冉冉', '小琪', '佳瑞', '丫头', ] // const studentIndexs = students.map((v, i) => i) const studentIndexs = students.map( function(elm,i) { return i; }); total.innerHTML = students.length; students.sort(() => 0.5 - Math.random()); students.forEach(v => { const li = document.createElement('li') li.innerHTML = v name_box.appendChild(li) }) let intervalId = null; btn.addEventListener('click', () => { // console.log(students.map((v, i) => i)) // .sort(() => 0.5 - Math.random()) // console.log(students.map((v, i) => i).sort(() => 0.5 - Math.random())) // 已开启,就停止 let yi = [...name_box.children]; // 这里作用:数组解构: 1. 将伪数组转换为真数组 2.把 [] 去除,将拓展运算符数组中的每一个数据项都拿出来,单独作为一个数据项 console.log(yi) if (intervalId) { btn.innerHTML = `点击随机抽取 ${size} 位` clearInterval(intervalId) intervalId = null } // 未开启,就开启 , 此时是还没有开启的状态, 点击后立马开启 else { btn.innerHTML = '确定选择' intervalId = setInterval(() => { yi.forEach(li => { li.classList.remove('active') }) const selectStudentIndexs = studentIndexs.sort(() => 0.5 - Math.random()).slice(0, size) selectStudentIndexs.forEach(v => { name_box.children[v].classList.add('active') }) }, 20); } }) sizeInput.addEventListener('blur', (e) => { // console.log(e.target.value) size = parseInt(e.target.value) btn.innerHTML = `点击随机抽取 ${size} 位` }) })(); </script> </body> </html>
    Processed: 0.008, SQL: 10