应使用 font-size 控制文字尺寸并用 rem 驱动全局响应,避免 zoom 和 transform: scale();通过动态设置 document.documentelement.style.fontsize 并配合 localstorage 保存偏好,确保无障碍、打印及布局一致性。

直接放大“整个网页”不是标准做法,浏览器级缩放(Ctrl+ 或 viewport)由用户控制,前端不应越权接管;真正该做的是:**用 font-size 控制文字尺寸,用 rem 驱动全局响应,同时避开 zoom 和 transform: scale() 这两个坑。**
为什么不能用 zoom 或 transform: scale()
这两个看似省事,实则破坏性极强:zoom 是非标准属性,Chrome 已弃用,Firefox 完全不支持;transform: scale() 只缩放像素渲染结果,不改变文档流尺寸——按钮点击热区错位、行高/间距/滚动高度全乱套,屏幕阅读器读的还是原始字号,打印时也退回原样。真要改“可读性”,就得动 font-size。
用 document.documentElement.style.fontSize 控制根字号
这是最稳定、无障碍友好、且能联动所有 rem 元素的方式。初始设 html { font-size: 16px; },再通过 JS 动态改根字体:
const root = document.documentElement;
let currentSize = 16;
function changeFontSize(delta) {
currentSize = Math.min(24, Math.max(12, currentSize + delta)); // 限制在 12–24px
root.style.fontSize = `${currentSize}px`;
localStorage.setItem('fontSize', currentSize);
}
// 页面加载时恢复上次设置
if (localStorage.getItem('fontSize')) {
currentSize = parseInt(localStorage.getItem('fontSize'));
root.style.fontSize = `${currentSize}px`;
}
- 每次变更都写入
localStorage,刷新不丢偏好 - 用
Math.min/Math.max硬限制范围,避免文字小到看不见或大到撑破布局 - 所有用
rem写的排版(margin、padding、line-height)会自动同比例缩放,不用额外处理
按钮交互必须带状态反馈和禁用逻辑
光有缩放不行,按钮得“知道自己在哪一档”。三态(小/正常/大)不能只靠 classList.toggle(),得用显式状态变量:
let fontSizeState = 'normal'; // 'small', 'normal', 'large'
function updateButtonState() {
enlargeBtn.disabled = fontSizeState === 'large';
shrinkBtn.disabled = fontSizeState === 'small';
enlargeBtn.setAttribute('aria-label', fontSizeState === 'large' ? '已达最大字号' : '放大文字');
shrinkBtn.setAttribute('aria-label', fontSizeState === 'small' ? '已达最小字号' : '缩小文字');
}
- 必须设
disabled属性,配合 CSS 的opacity: 0.5; pointer-events: none;视觉+交互双重禁用 -
aria-label要动态更新,让屏幕阅读器知道当前不可操作的原因 - 按钮本身用
<button type="button"></button>,防止意外触发表单提交
最容易被忽略的一点:改了 html 的 font-size 后,如果按钮、段落、标题的内边距或行高是用 px 写的,它们就不会跟着变——必须统一用 rem,否则“放大文字”只放大了字,没放大可点击区域和呼吸感。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











