做圖片展示、素材檢索一類的網站時,使用者往往希望能「用眼睛挑顏色」,而不是背十六進位色碼。這個只有 4K 出頭的老腳本示範了一個相當經典的做法:用 JavaScript 即時畫出一張全彩的色盤表格,滑過就預覽、點擊就取值,再把結果塞進表單欄位一起送出。
核心思路是用三個陣列 aR、aG、aB 預先鋪開整條色域,再以 64×64 的格子(每格 2px)把色彩空間「切」成網格。滑鼠移入某格時讀取該格的 bgColor,寫進預覽區;點擊時則把色值寫入隱藏欄位 rgb,之後隨表單一起 POST 到後端。
<form name="recherche" method="post" action="yourpage.html">
<input type="hidden" name="rgb" value="">
<table style="background-color:#f6f6f6;border:1px dotted #666;padding:5px;margin:0 auto;">
<tr>
<td align="right">Color:<br><small>滑過可預覽,點擊可選取</small></td>
<td style="border:1px outset #CCF;background-color:#ffe;">
<div id="temoin" style="float:right;width:40px;height:128px;"></div>
<script type="text/javascript">
var total = 1657, X, Y, j, R, G, B, i;
var aR = new Array(total), aG = new Array(total), aB = new Array(total);
// 攤開 RGB 色域
for (i = 0; i < 256; i++) {
aR[i+510] = aR[i+765] = aG[i+1020] = aG[i+5*255] = aB[i] = aB[i+255] = 0;
aR[510-i] = aR[i+1020] = aG[i] = aG[1020-i] = aB[i+510] = aB[1530-i] = i;
aR[i] = aR[1530-i] = aG[i+255] = aG[i+510] = aB[i+765] = aB[i+1020] = 255;
if (i < 255) { aR[i/2+1530] = aG[i/2+1530] = aB[i/2+1530] = 127; }
}
// 點擊:把色值寫入預覽區與隱藏欄位
function p() {
var el = document.getElementById('choix');
el.innerHTML = artabus;
el.style.backgroundColor = artabus;
document.forms['recherche'].rgb.value = artabus;
}
var hexbase = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
var jl = [], k = 0, x, y;
for (x = 0; x < 16; x++) for (y = 0; y < 16; y++) jl[k++] = hexbase[x] + hexbase[y];
document.write('<table border="0" cellspacing="0" cellpadding="0" onMouseover="t(event)" onClick="p()">');
var H = W = 63;
for (Y = 0; Y <= H; Y++) {
s = '<tr height="2">';
j = Math.round(Y * (510 / (H + 1)) - 255);
for (X = 0; X <= W; X++) {
i = Math.round(X * (total / W));
R = aR[i] - j; if (R < 0) R = 0; if (R > 255 || isNaN(R)) R = 255;
G = aG[i] - j; if (G < 0) G = 0; if (G > 255 || isNaN(G)) G = 255;
B = aB[i] - j; if (B < 0) B = 0; if (B > 255 || isNaN(B)) B = 255;
s += '<td width="2" bgcolor="#' + jl[R] + jl[G] + jl[B] + '"></td>';
}
document.write(s + '</tr>');
}
document.write('</table>');
var ns6 = document.getElementById && !document.all;
var ie = document.all;
var artabus = '';
// 滑過:更新預覽色塊
function t(e) {
var source = ie ? event.srcElement : e.target;
if (source.tagName == "TABLE") return;
while (source.tagName != "TD" && source.tagName != "HTML")
source = ns6 ? source.parentNode : source.parentElement;
document.getElementById('temoin').style.backgroundColor = artabus = source.bgColor;
}
</script>
<div id="choix" style="height:24px;"
onClick="document.forms['recherche'].rgb.value='';this.style.backgroundColor=''"></div>
</td>
</tr>
<tr><td colspan="2" align="center"><input type="submit"></td></tr>
</table>
</form>
<td> 靠 document.write 一次吐出,在當年的瀏覽器上比用 Canvas 現實得多。e.target,IE 走 event.srcElement,再往上找父節點直到命中 TD。#choix 的 onclick 同時清空色值與背景,方便重新挑選。<input type="color"> 或 Canvas 會短很多,但這份腳本仍是理解「色彩空間如何映射成網格」的好教材。原始出處:interclasse.com 的 4K script 收藏。