透過 `setInterval` 定時修改元素 `fontSize` 與 `color`,可製作閃爍、呼吸、彩虹等視覺特效。本文提供基礎版、可配置版與現代 CSS 動畫替代方案。
<div id="dynamic-text" style="font-size: 20px;">
你好,這是一段會變大小、變顏色的文字特效
</div>
<script>
const el = document.getElementById('dynamic-text');
let size = 20;
let direction = 1; // 1: 變大, -1: 變小
const MIN_SIZE = 20, MAX_SIZE = 60;
const SPEED = 200; // ms
function getRandomColor() {
// 產生隨機十六進位顏色 #RRGGBB
return '#' + Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0');
}
function animate() {
// 更新大小
size += direction;
if (size >= MAX_SIZE) direction = -1;
if (size <= MIN_SIZE) direction = 1;
el.style.fontSize = size + 'px';
// 更新顏色
el.style.color = getRandomColor();
}
setInterval(animate, SPEED);
</script>
class TextAnimator {
constructor(selector, options = {}) {
this.elements = [...document.querySelectorAll(selector)];
this.options = {
minSize: 16,
maxSize: 48,
step: 1,
interval: 200,
colorMode: 'random', // 'random' | 'rainbow' | 'fixed' | function
fixedColor: '#ff0000',
...options
};
this.timer = null;
this.hue = 0;
}
start() {
if (this.timer) return;
this.timer = setInterval(() => this.tick(), this.options.interval);
}
stop() {
clearInterval(this.timer);
this.timer = null;
}
destroy() {
this.stop();
this.elements.forEach(el => {
el.style.fontSize = '';
el.style.color = '';
});
}
tick() {
this.elements.forEach(el => {
// 字體大小來回縮放
const currentSize = parseFloat(el.style.fontSize) || this.options.minSize;
let newSize = currentSize + this.options.step * (this.direction || 1);
if (newSize >= this.options.maxSize) { newSize = this.options.maxSize; this.direction = -1; }
if (newSize <= this.options.minSize) { newSize = this.options.minSize; this.direction = 1; }
el.style.fontSize = newSize + 'px';
// 顏色模式
switch (this.options.colorMode) {
case 'random':
el.style.color = '#' + Math.floor(Math.random()*0xffffff).toString(16).padStart(6,'0');
break;
case 'rainbow':
el.style.color = `hsl(${this.hue}, 100%, 50%)`;
this.hue = (this.hue + 10) % 360;
break;
case 'fixed':
el.style.color = this.options.fixedColor;
break;
default:
if (typeof this.options.colorMode === 'function') {
el.style.color = this.options.colorMode(el);
}
}
});
}
}
// 使用
const animator = new TextAnimator('#dynamic-text', {
minSize: 20, maxSize: 60, interval: 200, colorMode: 'rainbow'
});
animator.start();
// 頁面隱藏時暫停,節省資源
document.addEventListener('visibilitychange', () => {
if (document.hidden) animator.stop();
else animator.start();
});
@keyframes font-size-pulse {
0%, 100% { font-size: 20px; }
50% { font-size: 60px; }
}
@keyframes color-rainbow {
0% { color: hsl(0, 100%, 50%); }
16% { color: hsl(60, 100%, 50%); }
33% { color: hsl(120, 100%, 50%); }
50% { color: hsl(180, 100%, 50%); }
66% { color: hsl(240, 100%, 50%); }
83% { color: hsl(300, 100%, 50%); }
100% { color: hsl(360, 100%, 50%); }
}
.dynamic-text {
animation:
font-size-pulse 4s ease-in-out infinite,
color-rainbow 8s linear infinite;
}
/* 尊重使用者偏好減少動畫 */
@media (prefers-reduced-motion: reduce) {
.dynamic-text { animation: none; }
}
**優勢:** 由瀏覽器合成器執行(不佔主執行緒)、60fps 流暢、可被 `prefers-reduced-motion` 停用、無 JS 依賴。
| 方案 | 主執行緒佔用 | 幀率穩定度 | 記憶體 | 可維護性 |
|---|---|---|---|---|
| JS setInterval | 高(每幀觸發 JS、佈局、繪製) | 易掉幀 | 低 | 中(邏輯分散) |
| JS requestAnimationFrame | 中 | 較好 | 低 | 中 |
| CSS Animation | 極低(合成器執行) | 最佳 | 極低 | 高(宣告式) |
**結論:** 能用 CSS Animation 解決的視覺特效,**絕不**用 JS 實作。保留 JS 版本僅供學習邏輯或極特殊動態需求(如根據資料即時計算顏色)。