利用 JavaScript HSB 色相循環,讓滑鼠經過的超連結文字呈現持續變色的彩虹動畫效果。代碼相容 IE4+,現代瀏覽器亦可運行。
document.onmouseover,判斷目標元素為 <a> 且有 href。setInterval 每 100ms 呼叫 ChangeColor()。makeColor() 以 HSB 色空間計算,色相 H 每次遞增 rate(預設 20),轉換為 RGB 十六進位色碼套用至 element.style.color。onmouseout 時恢復原色並 clearInterval。<style>
a:link, a:visited { color: #0066CC; text-decoration: none; }
a:hover, a:active { text-decoration: none; }
</style>
<script>
var rate = 20, obj, act = 0, elmH = 0, elmS = 128, elmV = 255, clrOrg, TimerID;
var isIE = navigator.appName.indexOf("Microsoft") != -1 && parseInt(navigator.appVersion) >= 4;
if (isIE) {
document.onmouseover = doRainbowAnchor;
document.onmouseout = stopRainbowAnchor;
}
function doRainbowAnchor() {
if (!isIE || act) return;
obj = event.srcElement;
while (obj.tagName != 'A' && obj.tagName != 'BODY') obj = obj.parentElement;
if (obj.tagName == 'A' && obj.href) {
act = 1; clrOrg = obj.style.color;
TimerID = setInterval(ChangeColor, 100);
}
}
function stopRainbowAnchor() {
if (isIE && act && obj.tagName == 'A') {
obj.style.color = clrOrg; clearInterval(TimerID); act = 0;
}
}
function ChangeColor() { obj.style.color = makeColor(); }
function makeColor() {
var elmR, elmG, elmB, t1, t2, t3;
if (elmS == 0) { elmR = elmG = elmB = elmV; }
else {
t1 = elmV; t2 = (255 - elmS) * elmV / 255; t3 = elmH % 60;
t3 = (t1 - t2) * t3 / 60;
if (elmH < 60) { elmR = t1; elmB = t2; elmG = t2 + t3; }
else if (elmH < 120) { elmG = t1; elmB = t2; elmR = t1 - t3; }
else if (elmH < 180) { elmG = t1; elmR = t2; elmB = t2 + t3; }
else if (elmH < 240) { elmB = t1; elmR = t2; elmG = t1 - t3; }
else if (elmH < 300) { elmB = t1; elmG = t2; elmR = t2 + t3; }
else if (elmH < 360) { elmR = t1; elmG = t2; elmB = t1 - t3; }
else { elmR = elmG = elmB = 0; }
}
elmR = Math.floor(elmR); elmG = Math.floor(elmG); elmB = Math.floor(elmB);
var hex = '#' + elmR.toString(16).padStart(2,'0') + elmG.toString(16).padStart(2,'0') + elmB.toString(16).padStart(2,'0');
elmH = (elmH + rate) % 360;
return hex;
}
</script>
<div align="center"><a href="#">三聯網</a></div>
/* 純 CSS 漸變動畫 */
@keyframes rainbow {
0% { color: #f00; } 16% { color: #ff0; } 33% { color: #0f0; }
50% { color: #0ff; } 66% { color: #00f; } 83% { color: #f0f; }
100% { color: #f00; }
}
a:hover { animation: rainbow 3s linear infinite; }
CSS 動畫效能更佳、無 JS 阻塞、支援所有現代瀏覽器(含行動裝置),建議優先採用。