網頁裡的顏色效果大致分兩類:顏色梯度變化(一次算出一整段過渡色),以及顏色動態漸變(讓顏色隨時間慢慢改變)。本文把這兩件事各自封裝成一個可重複使用的模組。
ColorGrads 的作用是依「顏色集合」與「漸變級數」算出整段過渡色。級數就是要把轉換切成幾步。
CSS 顏色採用 RGB 模式,每種顏色由紅(r)、綠(g)、藍(b)三個 0~255 的數值組成。W3C 定義的寫法有幾種,其實都指同一顏色:
em { color: red; }
em { color: #f00; }
em { color: #ff0000; }
em { color: rgb(255, 0, 0); }
em { color: rgb(100%, 0%, 0%); }
麻煩的是各瀏覽器讀回來的形式並不一致:IE 的 currentStyle 會保留關鍵字原樣,Firefox/Chrome/Safari 的 getComputedStyle 則一律轉成 rgb(255, 0, 0);而 Opera 用 currentStyle 讀關鍵字時,回傳值還會帶一層雙引號,相當惱人。
所以要計算梯度,第一步是把各種寫法都正規化成 RGB 陣列。這個工作由 GetData 完成:
function GetData(color) {
var re = RegExp;
if (/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.test(color)) { // #rrggbb
return $$A.map([ re.$1, re.$2, re.$3 ], function(x){
return parseInt(x, 16);
});
} else if (/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test(color)) { // #rgb
return $$A.map([ re.$1, re.$2, re.$3 ], function(x){
return parseInt(x + x, 16);
});
} else if (/^rgb\((.*),(.*),(.*)\)$/i.test(color)) { // rgb(n,n,n) 或百分比
return $$A.map([ re.$1, re.$2, re.$3 ], function(x){
return x.indexOf("%") > 0 ? parseFloat(x, 10) * 2.55 : x | 0;
});
}
}
注意 parseInt 的第二個參數要給 16,才能正確處理十六進位字串。
關鍵字形式(如 red)就沒這麼好辦了。硬塞一份完整對照表會讓檔案膨脹,這裡借用一個巧妙的技巧:建立一個隱藏的 textarea,把 color 設上去,再用 queryCommandValue("ForeColor") 反查數值。
var frag;
if (!frag) {
frag = document.createElement("textarea");
frag.style.display = "none";
document.body.insertBefore(frag, document.body.childNodes[0]);
}
try { frag.style.color = color; } catch(e) { return [0, 0, 0]; }
if (document.defaultView) { // 支援 getComputedStyle 的瀏覽器
ret = GetData(document.defaultView.getComputedStyle(frag, null).color);
} else { // IE 走 queryCommandValue
color = frag.createTextRange().queryCommandValue("ForeColor");
ret = [ color & 0x0000ff, (color & 0x00ff00) >>> 8, (color & 0xff0000) >>> 16 ];
}
這裡有兩個坑要記住:一是 insertBefore 而非 appendChild,可避開 IE 的已知 bug;二是 queryCommandValue 回傳的數值是 BGR 排列(例如粉紅 #FFC0CB 會得到 13353215),所以要靠位元運算把順序倒回來。用 & 取出對應位元組,再用 >>> 移到正確位置即可。
有了 RGB 陣列,算步長就只是小學除法:
stepR = (end[0] - start[0]) / step;
stepG = (end[1] - start[1]) / step;
stepB = (end[2] - start[2]) / step;
for (var i = 0, r = start[0], g = start[1], b = start[2]; i < step; i++) {
colors[i] = [r, g, b];
r += stepR; g += stepG; b += stepB;
}
colors[i] = end;
最後務必把結果夾在 0~255 之間並取整數,否則 rgb() 會失效:
return $$A.map(colors, function(x){
return $$A.map(x, function(x){
return Math.min(Math.max(0, Math.floor(x)), 255);
});
});
支援多段顏色時,只要相鄰兩兩計算再串接,記得把接縫處重複的顏色去掉:
for (var i = 0, n = len - 1; i < n; i++) {
var steps = GetStep(colors[i], colors[i + 1], step);
i < n - 1 && steps.pop();
ret = ret.concat(steps);
}
有了梯度陣列,漸變就只是「按時序把陣列內容依序套上去」。核心是移動索引:漸入讓索引遞增,漸出讓索引遞減。
transIn: function() {
this.stop();
this._index++;
this._set();
if (this._index < this._colors.length - 1) {
this._timer = setTimeout($$F.bind(this.transIn, this), this.speed);
}
},
transOut: function() {
this.stop();
this._index--;
this._set();
if (this._index > 0) {
this._timer = setTimeout($$F.bind(this.transOut, this), this.speed);
}
},
_set: function() {
var color = this._colors[Math.min(Math.max(0, this._index), this._colors.length - 1)];
this._elem.style[this.style] = "rgb(" + color.join(",") + ")";
}
this.style 決定要動哪個屬性:"color" 是文字色,"backgroundColor" 是背景色。若起始色、結束色或級數需要變更,得呼叫 reset() 重新產生梯度陣列並把索引歸零。
// 產生梯度
ColorGrads(colors, step); // colors 為顏色陣列,step 為級數(預設 20)
// 建立漸變物件
new ColorTrans(elem, {
from: "", // 起始色,留空則自動抓取目前樣式
to: "#000", // 結束色
step: 20, // 漸變級數
speed: 20, // 每步間隔(毫秒)
style: "color" // 要改變的樣式屬性
});
實際應用上,這個模組可以拿來做顏色梯度展示條、色票拾取器、選單 hover 漸變,甚至點擊隨機換色。文中範例就實作了這四種:
第一,<a> 的偽類(如 :hover)顏色沒辦法直接用 DOM 改,除非去動 class。選單範例的解法是把 a 的內容與連結搬到 td 上:
var a = x.getElementsByTagName("a")[0], href = a.href, txt = a.innerHTML;
x.onclick = function(){ location.href = href; };
x.innerHTML = txt;
這樣既做出效果,又不影響原本的可使用性。
第二,一個跨瀏覽器的陣列小陷阱:alert([,,].length) 在 IE 回傳 3,其他瀏覽器回傳 2。依 ECMAScript 規範,陣列字面值結尾的逗號會被忽略,所以寫程式時別依賴這種模糊行為。
另外提醒,設定 rgb() 時請依標準用逗號分隔、數值不要與百分比混用——IE6/IE7 寬鬆允許這些寫法,但 IE8 與其他瀏覽器都不接受。至於某些舊文件上寫的 rgb 1.0 0.0 0.0,那是無效寫法,別被誤導。