萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 字體大小切換器:大中小三檔控制提升閱讀體驗

效果預覽

頁面頂部提供「大/中/小」三個鏈接,點擊即時調整文章區域字體大小,並可持久化到 localStorage。

基礎版(原生 JS)

<div id="article">
  <p>文章內容...</p>
</div>
<div class="font-controls">
  <a href="#" data-size="20">大</a>
  <a href="#" data-size="16">中</a>
  <a href="#" data-size="12">小</a>
</div>

<script>
function setFontSize(size) {
  document.getElementById('article').style.fontSize = size + 'px';
  localStorage.setItem('fontSize', size);
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
  var saved = localStorage.getItem('fontSize');
  if (saved) setFontSize(parseInt(saved));

  document.querySelectorAll('.font-controls a').forEach(function(a) {
    a.addEventListener('click', function(e) {
      e.preventDefault();
      setFontSize(parseInt(this.dataset.size));
    });
  });
});
</script>

進階版:相對縮放 + 範圍限制 + 無障礙

class FontResizer {
  constructor(options = {}) {
    this.target = options.target || '#article';
    this.min = options.min || 12;
    this.max = options.max || 24;
    this.step = options.step || 2;
    this.defaultSize = options.defaultSize || 16;
    this.storageKey = options.storageKey || 'fontSize';
    this.$target = document.querySelector(this.target);
    this.init();
  }

  init() {
    // 恢復保存值
    const saved = localStorage.getItem(this.storageKey);
    this.currentSize = saved ? Math.max(this.min, Math.min(this.max, parseInt(saved))) : this.defaultSize;
    this.apply();

    // 綁定按鈕
    document.querySelectorAll('[data-font-action]').forEach(btn => {
      btn.addEventListener('click', e => {
        e.preventDefault();
        const action = btn.dataset.fontAction;
        if (action === 'increase') this.increase();
        else if (action === 'decrease') this.decrease();
        else if (action === 'reset') this.reset();
        else if (action.startsWith('set:')) this.set(parseInt(action.split(':')[1]));
      });
    });

    // 鍵盤快捷鍵 Ctrl/Cmd + +/-/0
    document.addEventListener('keydown', e => {
      if (e.ctrlKey || e.metaKey) {
        if (e.key === '+' || e.key === '=') { e.preventDefault(); this.increase(); }
        else if (e.key === '-') { e.preventDefault(); this.decrease(); }
        else if (e.key === '0') { e.preventDefault(); this.reset(); }
      }
    });
  }

  apply() { this.$target.style.fontSize = this.currentSize + 'px'; }
  increase() { this.set(this.currentSize + this.step); }
  decrease() { this.set(this.currentSize - this.step); }
  reset() { this.set(this.defaultSize); }
  set(size) {
    this.currentSize = Math.max(this.min, Math.min(this.max, size));
    this.apply();
    localStorage.setItem(this.storageKey, this.currentSize);
    this.announce();
  }
  announce() {
    // 無障礙:通知屏幕閱讀器
    const live = document.getElementById('font-announce') || document.createElement('div');
    live.id = 'font-announce'; live.setAttribute('role', 'status'); live.setAttribute('aria-live', 'polite');
    live.style.position = 'absolute'; live.style.left = '-9999px';
    live.textContent = `字體大小已調整為 ${this.currentSize} 像素`;
    document.body.appendChild(live);
  }
}

// 使用
new FontResizer({ target: '#article', min: 12, max: 28, step: 2 });

HTML 控制按鈕

<div class="font-controls" role="group" aria-label="字體大小">
  <button data-font-action="decrease" aria-label="縮小字體">A-</button>
  <button data-font-action="reset" aria-label="恢復默認">A</button>
  <button data-font-action="increase" aria-label="放大字體">A+</button>
</div>

CSS 相對單位配合(推薦)

:root { --base-font: 16px; }
html { font-size: var(--base-font); }
body { font-size: 1rem; } /* 所有字體用 rem */

// JS 只需修改根元素
document.documentElement.style.fontSize = size + 'px';

優勢:全站字體同步縮放、不破壞相對佈局、無需遍歷所有元素。

總結

字體大小切換是無障礙訪問的基本要求。現代做法:CSS rem 基準 + JS 修改 html font-size + localStorage 持久化 + 鍵盤快捷鍵 + ARIA 宣告。代碼量極小,體驗提升顯著,建議所有內容型網站標配。

copyright © 萬盛學電腦網 all rights reserved