需要在網頁嵌入顏色選擇器?本文提供零依賴、原生 JavaScript 實作,生成完整 4096 色調色盤(16×16×16),支援點擊選色、滑鼠懸停預覽、輸入框同步,適合嵌入 CMS、表單、設計工具等場景。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML 顏色選擇器 Demo</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans TC", sans-serif; padding: 20px; background: #f5f5f5; }
.container { max-width: 900px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
h1 { font-size: 1.5rem; margin-bottom: 1rem; color: #333; }
.color-input { width: 100%; padding: 12px; font-size: 1.1rem; border: 3px solid #333; border-radius: 4px; margin-bottom: 16px; text-align: center; font-family: monospace; }
.palette { display: flex; flex-wrap: wrap; gap: 1px; border: 1px solid #ddd; border-radius: 4px; overflow: hidden; }
.color-cell { width: 16px; height: 16px; cursor: pointer; transition: transform 0.1s; }
.color-cell:hover { transform: scale(1.5); z-index: 10; box-shadow: 0 2px 6px rgba(0,0,0,0.3); }
.gray-strip { display: flex; gap: 1px; margin-bottom: 8px; }
.gray-cell { width: 16px; height: 16px; cursor: pointer; }
.legend { margin-top: 16px; font-size: 0.875rem; color: #666; line-height: 1.6; }
</style>
</head>
<body>
<div class="container">
<h1>🎨 HTML 原生顏色選擇器 (4096 色)</h1>
<input type="text" id="colorInput" class="color-input" value="#000000" readonly placeholder="點選下方色格或手動輸入 #RRGGBB">
<div class="gray-strip" id="grayStrip"></div>
<div class="palette" id="palette"></div>
<p class="legend">
操作說明:
• 點擊任意色格 → 選取顏色,輸入框同步更新
• 滑鼠懸停色格 → 輸入框邊框即時預覽
• 輸入框可手動輸入 #RRGGBB 格式色碼
• 灰階色條獨立顯示,方便選擇中性灰
</p>
</div>
<script>
const input = document.getElementById('colorInput');
const palette = document.getElementById('palette');
const grayStrip = document.getElementById('grayStrip');
const hex = '0123456789ABCDEF';
// 灰階色條 (R=G=B)
for (let i = 0; i < hex.length; i++) {
const c = hex[i];
const color = `#${c}${c}${c}`;
const cell = document.createElement('div');
cell.className = 'gray-cell';
cell.style.backgroundColor = color;
cell.title = color;
cell.onclick = () => selectColor(color);
cell.onmouseover = () => previewColor(color);
grayStrip.appendChild(cell);
}
// 主調色盤:16 組 (R 固定),每組 16×16 (G×B)
for (let r = 0; r < hex.length; r++) {
const strip = document.createElement('div');
strip.style.display = 'flex';
strip.style.flexWrap = 'wrap';
for (let g = 0; g < hex.length; g++) {
for (let b = 0; b < hex.length; b++) {
const color = `#${hex[r]}${hex[g]}${hex[b]}`;
const cell = document.createElement('div');
cell.className = 'color-cell';
cell.style.backgroundColor = color;
cell.title = color;
cell.onclick = () => selectColor(color);
cell.onmouseover = () => previewColor(color);
strip.appendChild(cell);
}
}
palette.appendChild(strip);
}
function selectColor(color) {
input.value = color;
input.style.borderColor = color;
input.style.backgroundColor = color;
input.style.color = getContrastColor(color);
}
function previewColor(color) {
input.style.borderColor = color;
}
// 計算對比色 (白/黑) 確保輸入框文字可讀
function getContrastColor(hexColor) {
const r = parseInt(hexColor.slice(1,3), 16);
const g = parseInt(hexColor.slice(3,5), 16);
const b = parseInt(hexColor.slice(5,7), 16);
const luminance = (0.299*r + 0.587*g + 0.114*b) / 255;
return luminance > 0.5 ? '#000' : '#fff';
}
// 初始化
selectColor('#000000');
// 支援手動輸入驗證
input.addEventListener('blur', () => {
if (/^#[0-9A-Fa-f]{6}$/.test(input.value)) {
selectColor(input.value.toUpperCase());
} else {
alert('格式錯誤:請輸入 #RRGGBB 格式');
input.value = '#000000';
selectColor('#000000');
}
});
</script>
</body>
</html>
| 技術點 | 說明 |
|---|---|
| DOM 動態生成 | 三層迴圈 `document.createElement` 建立 4096 個 div,避免 `document.write` 阻塞與 XSS 風險 |
| 事件委派優化 (進階) | 若效能敏感,可將 onclick/onmouseover 綁定在 palette 容器,用 `e.target.dataset.color` 判斷 |
| 對比色演算法 | YIQ 亮度公式 `(0.299*R + 0.587*G + 0.114*B) / 255` 決定文字黑/白 |
| CSS 變數替代方案 | 現代專案建議用 `` 原生選色器 + CSS 變數 `--color` 傳遞 |
| 無障礙 | 加上 `aria-label`、鍵盤可聚焦、色盲友善模式 (模擬滤鏡) |
<input type="color" id="nativePicker" value="#0099ff">
<script>
document.getElementById('nativePicker').addEventListener('input', (e) => {
console.log('選取顏色:', e.target.value); // 即時回調
});
</script>
這個 4096 色選擇器雖然經典,但在現代專案中,建議優先評估原生 `<input type="color">` 或成熟庫 (如 Pickr, Vanilla-Picker),僅在需要自訂調色盤 UI、離線環境、或教學示範時採用自製版本。