萬盛學電腦網

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

JavaScript 隨機生成網頁背景顏色:三槽位轉盤機制完整實現

效果描述

三組兩位十六進位色碼(R/G/B)以轉盤形式高速滾動,使用者點擊「X」停止各槽位,點擊「預覽」即時套用背景色。類似老虎機選色器。

核心邏輯

  1. 色碼字元池:['0','3','6','9','C','F'] → 6 級 Web 安全色階,組合成 216 種顏色。
  2. 三槽位獨立滾動:每槽位對應 R、G、B 兩位十六進位,獨立 setTimeout 循環更新。
  3. 停止控制:點擊「X」設定旗標停止該槽位,三槽皆停後加速滾動至極高速度(模擬定格)。
  4. 預覽與套用:組合三槽位當前值 #RRGGBB 設定 document.bgColor。

關鍵代碼片段

初始化與滾動

var color = ['0','3','6','9','C','F'];
var speed = 250;
var bg = ['FFFFFF','FFFFFF','FFFFFF']; // 三組完整色碼暫存

function roll(speedB) {
    // 槽位 1 (R)
    if (document.form.col1.value == ' X ') {
        document.form.c1.value = document.form.b1.value;
        document.form.b1.value = document.form.a1.value;
        document.form.a1.value = color[Math.round(Math.random()*10)%6] + color[Math.round(Math.random()*10)%6];
    }
    // 槽位 2 (G), 槽位 3 (B) 同理...
    setTimeout("roll(" + speedB + ")", speedB);
}

停止與預覽

function stop(col) {
    if (col==1) { document.form.col1.value=' '; i++; }
    if (col==2) { document.form.col2.value=' '; i++; }
    if (col==3) { document.form.col3.value=' '; i++; }
    if (i==3) {
        // 組合最終色碼
        bg[0] = document.form.a1.value + document.form.a2.value + document.form.a3.value;
        bg[1] = document.form.b1.value + document.form.b2.value + document.form.b3.value;
        bg[2] = document.form.c1.value + document.form.c2.value + document.form.c3.value;
        speedB = 500000; roll(speedB); // 極高速度實際停止
    }
}

function view(letter) {
    document.bgColor = bg[letter];
    document.form.color.value = '#' + bg[letter];
}

現代化重構:Canvas 色盤 / 原生 Color Picker

轉盤選色器屬於教學/娛樂性質,實務開發請直接使用:

<!-- 原生色彩選擇器,支援吸管、調色盤、透明度 -->
<input type="color" id="bg-color" value="#ffffff">

<script>
document.getElementById('bg-color').addEventListener('input', function(e) {
    document.body.style.backgroundColor = e.target.value;
});
</script>

若需自訂選色 UI:

  • 使用 <canvas> 繪製 HSV 色環 + 亮度滑塊。
  • 或引入成熟庫:iro.js, pickr, spectrum。
  • 輸出格式統一為 #RRGGBB 或 rgba(),配合 CSS 變數即時預覽。

結語

三槽位轉盤選色器是早期 JavaScript 動畫與表單交互的經典教學案例,展示了 setTimeout 遞歸動畫、表單控件操作、十六進位色碼組合等基礎技能。現代開發請直接使用 <input type="color"> 或成熟選色庫,專注於業務邏輯而非 UI 重造。

copyright © 萬盛學電腦網 all rights reserved