jQuery 的 animate() 不支援顏色屬性,這是一個老問題。除了改用 CSS3 transition 或引入 jQuery Color 插件之外,其實還有一條路:自己按幀插值計算 RGB。這個思路的好處是完全可控——顏色、時長、幀率都能自定義,也不依賴任何外部庫。
核心算法
漸變本質是「在起止顏色之間做線性插值」。給定起始色 from、目標色 to、總時長與總幀數,第 n 幀的紅色分量就是:
from.r × (總幀數 - n) / 總幀數 + to.r × n / 總幀數
綠、藍同理。然後用 setTimeout 按「每幀時長 × 當前幀序」的規則排隊觸發,就得到了平滑的過渡。
完整代碼
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>背景顏色漸變</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
</head>
<body>
<input id="Button1" type="button" value="button" onclick="tggg()" />
<script>
function tggg() {
fadeColor(
{ r: 0, g: 255, b: 0 }, // star color
{ r: 255, g: 255, b: 255 }, // end color
function (color) {
document.getElementById("asd").style.backgroundColor = color;
},
1, // 持續秒數
10 // 總幀數
);
}
// 所有代碼的執行時間只有 24 毫秒左右
function fadeColor(from, to, callback, duration, totalFrames) {
// 用一個函數來包裹 setTimeout,根據幀數來確定延時
function doTimeout(color, frame) {
setTimeout(function () {
try {
callback(color);
} catch (e) {
JSLog.write(e);
}
}, (duration * 1000 / totalFrames) * frame);
// 總持續秒數 / 每秒幀數 * 當前幀數 = 延時(秒),再乘以 1000 作為延時(毫秒)
}
// 整個漸變過程的持續時間,默認為 1 秒
var duration = duration || 1;
// 總幀數,默認為持續秒數 * 15 幀,也即每秒 15 幀
var totalFrames = totalFrames || duration * 15;
var r, g, b;
var frame = 1;
// 在第 0 幀設置起始顏色
doTimeout('rgb(' + from.r + ',' + from.g + ',' + from.b + ')', 0);
// 計算每次變化所需要改變的 rgb 值
while (frame < totalFrames + 1) {
r = Math.ceil(from.r * ((totalFrames - frame) / totalFrames) + to.r * (frame / totalFrames));
g = Math.ceil(from.g * ((totalFrames - frame) / totalFrames) + to.g * (frame / totalFrames));
b = Math.ceil(from.b * ((totalFrames - frame) / totalFrames) + to.b * (frame / totalFrames));
// 調用本 frame 的 doTimeout
doTimeout('rgb(' + r + ',' + g + ',' + b + ')', frame);
frame++;
}
}
</script>
<div style="width: 600px; height: 200px; border: 1px solid red;" id="asd">
歡迎各位光臨--https://www.jb51.net
</div>
</body>
</html>
代碼要點
一次性排隊而非遞歸調用。 這個實現先在 while 迴圈裡把全部幀的 setTimeout 排好,而不是等上一幀執行完再排下一幀。的好處是時間精度更高、不受回調耗時影響;代價是需要保存的定時器數量等於幀數。
延時公式。 (duration * 1000 / totalFrames) * frame——每幀時長乘以幀序號,即為該幀的絕對觸發時刻。第 0 幀延時為 0,立即設置起始色。
Math.ceil 的作用。 RGB 必須是整數,插值結果會出現小數,向上取整可避免 rgb(12.3,...) 這種非法值。嚴格來說用 Math.round 誤差更小,但差別不明顯。
callback 用 try/catch 包裹,避免單幀出錯導致後續全部中斷。示例中的 JSLog.write(e) 需要相應的日誌對象支持,實際使用時換成 console.error(e) 即可。
實用建議
這個方案適合理解原理和特殊場景下的定製需求,但如果只是想要「懸浮變色」這類常見效果,還是首選 CSS transition——瀏覽器原生實現,效能更好,代碼量也小得多。此外本實現不支援中途取消,若在快速連續觸發時需要打斷,可以借 jQuery.stop() 的思路記錄定時器 id 並批量 clear。
相關顏色與特效工具
在線特效文字/彩色文字生成工具:
https://tools.jb51.net/aideddesign/colortext
在線彩虹文字/顏色漸變文字生成工具:
https://tools.jb51.net/aideddesign/txt_caihongzi
在線發光字生成工具:
https://tools.jb51.net/aideddesign/txt_faguangzi
仿古書排版文字豎排轉換工具:
https://tools.jb51.net/transcoding/shupai