提供字體縮放功能是網頁無障礙(WCAG 1.4.4 Resize Text)的基本要求。本文示範純 JS 實作、現代 CSS `rem` 架構、使用者偏好記憶與無障礙增強。
// 字體大小階梯(對應 CSS 關鍵字)
const SIZE_KEYWORDS = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'];
const TARGET_TAGS = ['div', 'td', 'tr', 'p', 'span', 'li', 'a', 'body'];
let currentIndex = 3; // medium
function changeFontSize(delta) {
currentIndex = Math.max(0, Math.min(SIZE_KEYWORDS.length - 1, currentIndex + delta));
const size = SIZE_KEYWORDS[currentIndex];
TARGET_TAGS.forEach(tag => {
document.querySelectorAll(tag).forEach(el => {
el.style.fontSize = size;
});
});
// 記住使用者偏好
localStorage.setItem('fontSizeIndex', currentIndex);
}
// 初始化:讀取偏好
document.addEventListener('DOMContentLoaded', () => {
const saved = parseInt(localStorage.getItem('fontSizeIndex'), 10);
if (!isNaN(saved)) {
currentIndex = saved;
changeFontSize(0); // 套用不改變索引
}
});
<div class="font-controls" role="group" aria-label="字體大小調整">
<button type="button" onclick="changeFontSize(-1)" aria-label="縮小字體">A-</button>
<button type="button" onclick="changeFontSize(0)" aria-label="重設字體">A</button>
**核心原則:** 全站只用 `rem` 設定字體大小,調整 `` 的 `font-size` 即可全域縮放。
/* CSS */
html { font-size: 100%; } /* 16px 基準 */
body { font-size: 1rem; }
h1 { font-size: 2.5rem; }
.small-text { font-size: 0.875rem; }
/* JS 僅需調整根元素 */
function changeFontSize(delta) {
const html = document.documentElement;
const current = parseFloat(getComputedStyle(html).fontSize);
const newSize = Math.max(10, Math.min(32, current + delta * 2)); // 10px~32px 限制
html.style.fontSize = newSize + 'px';
localStorage.setItem('baseFontSize', newSize);
}
// 初始化
const saved = localStorage.getItem('baseFontSize');
if (saved) document.documentElement.style.fontSize = saved + 'px';
| 維度 | 傳統關鍵字法 | rem 根元素法 |
|---|---|---|
| 程式碼量 | 需遍歷所有元素 | 單行修改根元素 |
| 效能 | 大量 DOM 操作,易造成重繪 | 極佳,瀏覽器原生處理 |
| 比例關係 | 破壞原有相對比例 | 完美保持設計比例 |
| 響應式相容 | 困難 | 天然相容 |
| 支援自訂字體 | 有限 | 完整支援 |
/* CSS 偵測系統字體大小偏好 */
@media (prefers-reduced-motion: reduce) {
/* 使用者偏好減少動畫 */
}
@media (prefers-contrast: more) {
/* 高對比度模式 */
}
/* 現代瀏覽器支援 prefers-font-size(草案中) */
/* 未來可直接用 CSS 回應使用者系統設定 */
採用 `rem` 架構配合根元素縮放,是目前實作字體縮放最標準、效能最好、維護成本最低的方案。