萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實作隨機點名器:從基礎邏輯到完整互動效果

功能需求

  • 預設名單陣列,支援動態增減
  • 點擊「開始」按鈕或載入頁面自動快速切換顯示名字
  • 再次點擊「停止」鎖定當前名字
  • 視覺回饋:大字體、置中、邊框、游標變化
  • 程式碼精簡、無外部依賴、可直接嵌入頁面

完整 HTML + CSS + JS 整合範例

<!DOCTYPE html>
<html lang="zh-TW">
<head>
  <meta charset="UTF-8">
  <title>隨機點名器</title>
  <style>
    #nameDisplay {
      border: 2px solid #333;
      margin: 50px auto;
      font-size: 48px;
      color: #2c3e50;
      width: 300px;
      height: 80px;
      line-height: 80px;
      cursor: pointer;
      text-align: center;
      user-select: none;
      background: #f8f9fa;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
      transition: all 0.3s ease;
    }
    #nameDisplay:hover { background: #e9ecef; transform: scale(1.02); }
    #nameDisplay.running { animation: pulse 1s infinite; }
    @keyframes pulse { 0%,100% { box-shadow: 0 4px 12px rgba(0,0,0,0.1); } 50% { box-shadow: 0 4px 24px rgba(52,152,219,0.4); } }
    .controls { text-align: center; margin-top: 20px; }
    button { padding: 10px 24px; font-size: 16px; margin: 0 10px; border: none; border-radius: 4px; cursor: pointer; }
    .btn-start { background: #27ae60; color: white; }
    .btn-stop { background: #e74c3c; color: white; }
    .btn-reset { background: #95a5a6; color: white; }
  </style>
</head>
<body>
  <div id="nameDisplay">點擊開始</div>
  <div class="controls">
    <button class="btn-start" id="btnStart">開始點名</button>
    <button class="btn-stop" id="btnStop" disabled>停止點名</button>
    <button class="btn-reset" id="btnReset">重置名單</button>
  </div>

  <script>
    // 設定區
    var nameList = [
      '范鵬', '張子涵', '代天明', '孫季', '孫磊', '王鴻罡',
      '曾凡丁', '李歡', '朱穎', '王莎', '鄭琳琳', '朱振家',
      '金一', '李成龍', '苟超', '吳桐', '梁良', '劉俊'
    ];
    var intervalId = null;
    var isRunning = false;
    var $display = $('#nameDisplay');
    var $btnStart = $('#btnStart');
    var $btnStop = $('#btnStop');
    var $btnReset = $('#btnReset');

    // 核心邏輯
    function getRandomName() {
      return nameList[Math.floor(Math.random() * nameList.length)];
    }

    function startRolling() {
      if (isRunning || nameList.length === 0) return;
      isRunning = true;
      $display.addClass('running').text('...');
      $btnStart.prop('disabled', true);
      $btnStop.prop('disabled', false);
      
      intervalId = setInterval(function() {
        $display.text(getRandomName());
      }, 80);  // 80ms 切換一次,視覺上形成滾動效果
    }

    function stopRolling() {
      if (!isRunning) return;
      isRunning = false;
      clearInterval(intervalId);
      $display.removeClass('running');
      $btnStart.prop('disabled', false);
      $btnStop.prop('disabled', true);
      // 最後顯示一個隨機名字(已在 interval 最後一次執行時設定)
    }

    function resetList() {
      stopRolling();
      nameList = [
        '范鵬', '張子涵', '代天明', '孫季', '孫磊', '王鴻罡',
        '曾凡丁', '李歡', '朱穎', '王莎', '鄭琳琳', '朱振家',
        '金一', '李成龍', '苟超', '吳桐', '梁良', '劉俊'
      ];
      $display.text('點擊開始').removeClass('running');
    }

    // 事件綁定
    $btnStart.on('click', startRolling);
    $btnStop.on('click', stopRolling);
    $btnReset.on('click', resetList);
    
    // 點擊顯示區域也可切換開始/停止
    $display.on('click', function() {
      isRunning ? stopRolling() : startRolling();
    });

    // 鍵盤支援:空白鍵切換
    $(document).on('keydown', function(e) {
      if (e.code === 'Space' && e.target === document.body) {
        e.preventDefault();
        isRunning ? stopRolling() : startRolling();
      }
    });
  </script>
</body>
</html>

核心邏輯解析

1. 隨機選取

Math.floor(Math.random() * nameList.length)
// Math.random() 產生 [0, 1) 浮點數
// 乘以長度得 [0, length) 區間
// floor 取整得 0 ~ length-1 索引

2. 滾動效果實現

使用 setInterval 每 80ms 更新一次顯示文字,人眼視覺暫留效應產生「轉盤」感。停止時清除間隔,保留最後一次隨機結果。

3. 狀態管理

用 isRunning 布林旗標控制按鈕啟用/禁用、防止重複啟動計時器。intervalId 儲存計時器 ID 供清除。

功能擴充建議

加權隨機(權重點名)

var weightedList = [
  { name: '王小明', weight: 3 },  // 機率 3 倍
  { name: '李小華', weight: 1 },
  { name: '陳大同', weight: 2 }
];

function getWeightedRandom() {
  var total = weightedList.reduce((sum, item) => sum + item.weight, 0);
  var rand = Math.random() * total;
  for (var i = 0; i < weightedList.length; i++) {
    rand -= weightedList[i].weight;
    if (rand <= 0) return weightedList[i].name;
  }
  return weightedList[0].name;
}

歷史紀錄與不重複

var history = [];
var maxHistory = 5;

function getUniqueRandom() {
  var available = nameList.filter(function(name) {
    return history.indexOf(name) === -1;
  });
  if (available.length === 0) {
    history = [];  // 全部點過一輪,重置
    available = nameList.slice();
  }
  var picked = available[Math.floor(Math.random() * available.length)];
  history.push(picked);
  if (history.length > maxHistory) history.shift();
  return picked;
}

本地儲存名單

// 載入
var saved = localStorage.getItem('rollCallNames');
if (saved) nameList = JSON.parse(saved);

// 儲存
function saveList() {
  localStorage.setItem('rollCallNames', JSON.stringify(nameList));
}

語音播報(Web Speech API)

function speakName(name) {
  if ('speechSynthesis' in window) {
    var utter = new SpeechSynthesisUtterance(name);
    utter.lang = 'zh-TW';
    utter.rate = 0.9;
    speechSynthesis.speak(utter);
  }
}

// 在 stopRolling() 中呼叫 speakName($display.text())

無障礙與使用者體驗優化

  • ARIA 標籤:role="status" aria-live="polite" 讓螢幕報讀器讀出名字
  • 減少動畫:尊重 @media (prefers-reduced-motion: reduce),降低切換頻率或停用動畫
  • 鍵盤完整操作:Tab 切換按鈕、Enter/Space 觸發、Esc 停止
  • 高對比模式:CSS 變數管理色彩,支援系統深色模式

總結

這個隨機點名器展示了 JavaScript 核心概念:陣列操作、隨機數、定時器、狀態機、DOM 操作、事件處理。從 50 行基礎版擴充至功能完整版,適合教學示範、年會抽獎、課堂點名等場景。現代專案建議改用 Vue/React 狀態管理,將邏輯與視圖分離,並加入單元測試保證隨機公平性。

copyright © 萬盛學電腦網 all rights reserved