当前位置:首页 > JavaScript

js实现点名

2026-04-04 02:28:53JavaScript

js实现点名

js实现点名

实现点名功能的JavaScript代码

以下是一个简单的点名功能实现,包含随机选择和显示被点中的人名:

// 定义名单数组
const nameList = ['张三', '李四', '王五', '赵六', '钱七'];

// 获取DOM元素
const nameDisplay = document.getElementById('name-display');
const startBtn = document.getElementById('start-btn');
const stopBtn = document.getElementById('stop-btn');

let timer;
let isRolling = false;

// 开始点名
startBtn.addEventListener('click', () => {
  if (isRolling) return;
  isRolling = true;

  timer = setInterval(() => {
    const randomIndex = Math.floor(Math.random() * nameList.length);
    nameDisplay.textContent = nameList[randomIndex];
  }, 100);
});

// 停止点名
stopBtn.addEventListener('click', () => {
  if (!isRolling) return;
  clearInterval(timer);
  isRolling = false;
});

HTML结构示例

<div class="name-picker">
  <h2 id="name-display">准备开始</h2>
  <button id="start-btn">开始点名</button>
  <button id="stop-btn">停止</button>
</div>

CSS样式建议

.name-picker {
  text-align: center;
  margin-top: 50px;
}

#name-display {
  font-size: 32px;
  margin-bottom: 20px;
}

button {
  padding: 10px 20px;
  margin: 0 10px;
  font-size: 16px;
  cursor: pointer;
}

功能扩展建议

  1. 添加音效:在开始和停止时播放提示音增强体验
  2. 名单管理:增加添加/删除名单的功能
  3. 历史记录:保存已被点过名的人员
  4. 动画效果:使用CSS动画让名字滚动更生动
  5. 排除已点:避免重复点到同一个人

完整实现示例

class NamePicker {
  constructor(names = []) {
    this.names = names;
    this.pickedNames = new Set();
    this.isRolling = false;
    this.timer = null;
  }

  start(callback) {
    if (this.isRolling) return;
    this.isRolling = true;

    this.timer = setInterval(() => {
      const availableNames = this.names.filter(name => !this.pickedNames.has(name));
      if (availableNames.length === 0) {
        this.stop();
        return;
      }

      const randomIndex = Math.floor(Math.random() * availableNames.length);
      callback(availableNames[randomIndex]);
    }, 100);
  }

  stop() {
    if (!this.isRolling) return;
    clearInterval(this.timer);
    this.isRolling = false;
  }

  addName(name) {
    this.names.push(name);
  }

  reset() {
    this.pickedNames.clear();
  }
}

这个实现提供了更结构化的代码,便于扩展和维护。使用时只需创建NamePicker实例并调用相应方法即可。

标签: js
分享给朋友:

相关文章

js实现dh

js实现dh

JavaScript 实现 DH(Diffie-Hellman)密钥交换 Diffie-Hellman(DH)密钥交换是一种安全协议,允许双方在不安全的通信信道上建立一个共享密钥。以下是如何在 Jav…

js 实现跳转

js 实现跳转

使用 window.location.href 进行跳转 通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面: window.location.hre…

js实现下拉刷新

js实现下拉刷新

监听触摸事件 通过监听 touchstart、touchmove 和 touchend 事件来检测用户下拉手势。记录触摸起始位置和移动距离。 let startY = 0; let currentY…

js实现复制功能实现

js实现复制功能实现

使用document.execCommand方法(传统方式,已逐渐被弃用) 传统方式通过document.execCommand('copy')实现复制功能,需先选中文本。以下是一个完整示例: fu…

js实现刷新页面

js实现刷新页面

刷新页面的方法 在JavaScript中,可以通过多种方式实现页面刷新。以下是几种常见的方法: 使用 location.reload() 调用 location.reload() 方法可以重新加载当…

js 实现进度条

js 实现进度条

使用 HTML 和 CSS 创建基础结构 进度条需要一个容器和一个填充元素。HTML 结构可以简单如下: <div class="progress-container"> <d…