通過 setInterval 定時修改 DOM 元素的 fontSize 與 color 樣式,可實現文字大小脈動與隨機顏色變換的視覺特效。本文提供完整可運行代碼,並解析核心邏輯與優化方向。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>文字動態變化特效</title>
<style>
body { background: #000; min-height: 100vh; display: flex; justify-content: center; align-items: center; margin: 0; }
#text { font-size: 20px; font-weight: bold; transition: font-size 0.2s, color 0.2s; }
</style>
</head>
<body>
<div id="text">你好,這是一段改變文字大小和顏色的 JavaScript 代碼</div>
<script>
const textEl = document.getElementById('text');
let size = 20;
let direction = 1; // 1: 變大, -1: 變小
const MIN_SIZE = 20;
const MAX_SIZE = 60;
const STEP = 1;
const INTERVAL_MS = 200;
// 生成隨機十六進制顏色
function getRandomColor() {
// 方法 1: 簡潔現代寫法
return '#' + Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0');
// 方法 2: 原文邏輯(保留參考)
// const chars = '0123456789abcdef';
// let color = '#';
// for (let i = 0; i < 6; i++) {
// color += chars[Math.floor(Math.random() * 16)];
// }
// return color;
}
// 計算下一個字體大小(脈動效果)
function getNextSize() {
size += direction * STEP;
if (size >= MAX_SIZE) {
size = MAX_SIZE;
direction = -1;
} else if (size <= MIN_SIZE) {
size = MIN_SIZE;
direction = 1;
}
return size;
}
function animate() {
textEl.style.color = getRandomColor();
textEl.style.fontSize = getNextSize() + 'px';
}
// 啟動動畫
const timerId = setInterval(animate, INTERVAL_MS);
// 可選:頁面卸載時清理定時器
window.addEventListener('beforeunload', () => clearInterval(timerId));
</script>
</body>
</html>
direction 變量控制增減方向,邊界值反轉方向,形成平滑脈動。Math.random() * 0xffffff 生成 0~16777215 隨機數,.toString(16).padStart(6, '0') 轉為 6 位十六進制,比原文字符串拼接更高效。setInterval 每 200ms 執行一次,頻率適中(5 FPS),體驗流暢且不佔用過多資源。transition: font-size 0.2s, color 0.2s 使變化過渡自然,避免突兀跳變。function animateRAF() {
textEl.style.color = getRandomColor();
textEl.style.fontSize = getNextSize() + 'px';
requestAnimationFrame(animateRAF);
}
// 控制幀率:配合 timestamp 節流或 requestIdleCallback
優點:瀏覽器優化幀率、標籤頁隱藏自動暫停、無需手動清理定時器。
function getHarmoniousColor() {
const hue = (Date.now() / 50) % 360; // 緩慢旋轉色相
return `hsl(${hue}, 80%, 60%)`; // 固定飽和度與亮度,色相變化
}
比純隨機 RGB 視覺更協調,適合品牌色系場景。
class TextAnimator {
constructor(selector, options = {}) {
this.el = document.querySelector(selector);
this.minSize = options.minSize ?? 20;
this.maxSize = options.maxSize ?? 60;
this.step = options.step ?? 1;
this.interval = options.interval ?? 200;
this.colorMode = options.colorMode ?? 'random'; // 'random' | 'hsl' | 'custom'
this.customColors = options.customColors || [];
this.direction = 1;
this.size = this.minSize;
this.timerId = null;
}
start() {
if (this.timerId) return;
this.tick();
this.timerId = setInterval(() => this.tick(), this.interval);
}
stop() {
clearInterval(this.timerId);
this.timerId = null;
}
tick() {
this.el.style.fontSize = this.getNextSize() + 'px';
this.el.style.color = this.getNextColor();
}
getNextSize() { /* 同上脈動邏輯 */ }
getNextColor() { /* 根據 colorMode 返回顏色 */ }
}
// 使用
const animator = new TextAnimator('#text', { colorMode: 'hsl' });
animator.start();
fontSize 和 color 不會觸發回流,僅觸發重繪,性能影響極小。prefers-reduced-motion 媒體查詢。文字動態特效雖屬「花哨」範疇,但其核心技術——定時器/幀動畫驅動狀態機、隨機/算法生成視覺屬性、CSS transition 平滑過渡——是構建複雜 UI 動畫(如數字滾動、進度條、粒子特效)的基礎模塊。理解並靈活運用這些基礎模式,能讓你在需要時快速構建豐富的交互體驗。