萬盛學電腦網

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

JavaScript 實作隨機抽獎轉盤效果:從基礎邏輯到完整互動頁面

需求分析

點擊「開始」→ 獎項文字快速輪播 → 點擊「停止」→ 顯示中獎結果。核心技術點:

  • setInterval 高頻切換顯示文字
  • Math.random() 產生隨機索引
  • 按鈕狀態控制(開始/停止互斥)

精簡版核心邏輯(可直接嵌入專案)

<div id="prize" style="font-size:2rem; font-weight:bold; min-height:2em;">請點擊開始</div>
<button id="btnStart">開始</button>
<button id="btnStop" disabled>停止</button>
<input type="text" id="result" readonly placeholder="中獎結果">

<script>
const prizes = ['一等獎:iPhone 15', '二等獎:AirPods', '三等獎:星巴克券', '安慰獎:再接再厲', '謝謝惠顧'];
const elPrize = document.getElementById('prize');
const elResult = document.getElementById('result');
const btnStart = document.getElementById('btnStart');
const btnStop = document.getElementById('btnStop');

let timer = null;

function spin() {
  const idx = Math.floor(Math.random() * prizes.length);
  elPrize.textContent = prizes[idx];
}

btnStart.addEventListener('click', () => {
  if (timer) return;
  btnStart.disabled = true;
  btnStop.disabled = false;
  elResult.value = '';
  timer = setInterval(spin, 50); // 50ms 換一次,視覺上像轉盤
});

btnStop.addEventListener('click', () => {
  if (!timer) return;
  clearInterval(timer);
  timer = null;
  btnStart.disabled = false;
  btnStop.disabled = true;
  elResult.value = elPrize.textContent; // 定格當下顯示的獎項
});
</script>

進階強化版:加權機率、動畫緩動、防作弊

1. 加權機率(權重陣列)

const prizes = [
  { text: '一等獎:iPhone 15', weight: 1 },
  { text: '二等獎:AirPods', weight: 3 },
  { text: '三等獎:星巴克券', weight: 10 },
  { text: '安慰獎:再接再厲', weight: 30 },
  { text: '謝謝惠顧', weight: 56 }
];

// 建立權重池(或用累積權重二分搜尋)
const pool = prizes.flatMap(p => Array(p.weight).fill(p.text));

function spinWeighted() {
  const idx = Math.floor(Math.random() * pool.length);
  elPrize.textContent = pool[idx];
}

2. 停止時緩動動畫(CSS + JS)

// CSS
#prize { transition: transform 0.3s, opacity 0.3s; display: inline-block; }
#prize.stopping { transform: scale(1.1); opacity: 0.7; }

// JS 停止時
elPrize.classList.add('stopping');
setTimeout(() => elPrize.classList.remove('stopping'), 300);

3. 後端驗證防作弊(關鍵)

前端隨機僅供視覺效果,真實中獎邏輯必須在後端:

// 前端停止時發送請求
fetch('/api/lottery/draw', { method: 'POST' })
  .then(r => r.json())
  .then(data => {
    elPrize.textContent = data.prizeName; // 以後端結果為準
    elResult.value = data.prizeName;
  });

完整單檔案 Demo(含加權、動畫、鍵盤快捷鍵)

<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>抽獎轉盤</title>
<style>
  body{font-family:sans-serif;text-align:center;padding:2rem}
  #prize{font-size:2.5rem;font-weight:700;min-height:1.5em;transition:transform .3s,opacity .3s}
  #prize.spinning{animation:blur .1s linear infinite} @keyframes blur{to{text-shadow:0 0 4px #000}}
  button{font-size:1.2rem;padding:.6rem 1.5rem;margin:.5rem;cursor:pointer}
  button:disabled{opacity:.5;cursor:not-allowed}
  #result{font-size:1.2rem;padding:.5rem;width:80%;max-width:400px}
</style></head><body>
<div id="prize">點擊開始抽獎</div>
<button id="start" accesskey="s">開始 (S)</button>
<button id="stop" disabled accesskey="o">停止 (O)</button>
<br><input id="result" readonly placeholder="中獎結果將顯示這裡">
<script>
const prizes=[{t:'特獎🎉',w:1},{t:'一等獎🏆',w:2},{t:'二等獎🎁',w:5},{t:'三等獎☕',w:20},{t:'參加獎😊',w:72}];
const pool=prizes.flatMap(p=>Array(p.w).fill(p.t));
const $=id=>document.getElementById(id);
const el=$('prize'), btnS=$('start'), btnO=$('stop'), res=$('result');
let timer=null;
function spin(){el.textContent=pool[Math.random()*pool.length|0]}
btnS.onclick=()=>{if(timer)return;btnS.disabled=!0;btnO.disabled=!1;res.value='';el.classList.add('spinning');timer=setInterval(spin,50)};
btnO.onclick=()=>{if(!timer)return;clearInterval(timer);timer=null;btnS.disabled=!1;btnO.disabled=!0;el.classList.remove('spinning');res.value=el.textContent};
document.addEventListener('keydown',e=>{if(e.key==='s')btnS.click();if(e.key==='o')btnO.click()});
</script></body></html>

部署建議

  1. 獎項清單、權重從後端 API 取得,避免前端竄改。
  2. 記錄每次抽獎日誌(用戶、時間、結果、IP),便稽核。
  3. 大型活動建議引入抽獎服務(如抽獎箱演算法、防重複中獎)。

以上範例涵蓋從教學級到生產級的完整演進,可直接根據專案需求裁剪使用。

copyright © 萬盛學電腦網 all rights reserved