You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript点击按钮切换h1-h6标签字体大小

字号基准切换功能实现指引

现有代码问题

  • 当前CSS中两套字号规则选择器完全一致,根据CSS层叠规则,写在后面的18px样式会永久覆盖16px样式,无法实现切换效果。
  • 两个切换按钮class完全相同,没有区分标识,JS无法精准绑定对应事件。
  • 18px基准样式中h2、h5、h6的字号值遗漏px单位,会导致浏览器解析失效。

修正后的完整代码

CSS部分

/* 16px基准 Major Third 1.250 缩放因子 */
.main_container.size-16 > h1 {
  font-size: 31.25px;
}
.main_container.size-16 > h2 {
  font-size: 25px;
}
.main_container.size-16 > h3 {
  font-size: 20px;
}
.main_container.size-16 > h4 {
  font-size: 16px;
}
.main_container.size-16 > h5 {
  font-size: 12.8px;
}
.main_container.size-16 > h6 {
  font-size: 10.24px;
}
.main_container.size-16 > p {
  font-size: 16px;
}

/* 18px基准 Major Third 1.250 缩放因子 */
.main_container.size-18 > h1 {
 font-size: 35.16px;
}
.main_container.size-18 > h2 {
 font-size: 28.13px;
}
.main_container.size-18 > h3 {
  font-size: 22.5px;
}
.main_container.size-18 > h4 {
 font-size: 18px;
}
.main_container.size-18 > h5 {
 font-size: 14.4px;
}
.main_container.size-18 > h6 {
  font-size: 11.52px;
}
.main_container.size-18 > p {
  font-size: 18px;
}

/* 按钮选中态样式,标识当前生效的字号基准 */
button.active {
  background: #2563eb;
  color: #fff;
  border-color: #2563eb;
}

HTML部分

给按钮增加区分标识类,给内容容器加上默认的16px基准类:

<button class="size-btn size-16 active">Set 16px Typography</button>
<button class="size-btn size-18">Set 18px Typography</button>

<div class="main_container size-16">
  <h1>Almost before we knew it, we had left the ground.</h1>
  <h2>Almost before we knew it, we had left the ground.</h2>
  <h3>Almost before we knew it, we had left the ground.</h3>
  <h4>Almost before we knew it, we had left the ground.</h4>
  <h5>Almost before we knew it, we had left the ground.</h5>
  <h6>Almost before we knew it, we had left the ground.</h6>
  <p>Almost before we knew it, we had left the ground.</p>
</div>

JavaScript逻辑

把这段代码放在页面</body>标签前即可:

// 获取页面元素
const sizeButtons = document.querySelectorAll('.size-btn');
const mainContainer = document.querySelector('.main_container');

// 为所有切换按钮绑定点击事件
sizeButtons.forEach(btn => {
  btn.addEventListener('click', () => {
    // 判断当前点击的按钮对应哪套尺寸规则
    const targetSizeClass = btn.classList.contains('size-16') ? 'size-16' : 'size-18';
    
    // 切换内容容器的类名,仅需修改父容器类名即可全局生效
    mainContainer.classList.remove('size-16', 'size-18');
    mainContainer.classList.add(targetSizeClass);
    
    // 更新按钮选中状态
    sizeButtons.forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
  })
})

实现说明

  • 预定义两套样式再通过类名切换的思路完全可行,这种方式性能高、逻辑简单,非常适合固定排版主题切换场景,比JS动态遍历修改每个标签字号的方案更易维护。
  • 核心逻辑是通过父容器类名控制子元素样式匹配,不需要单独给每个标题、段落标签修改类名,仅切换父容器一个类名就能完成全文字号切换,代码冗余度极低。
  • 额外增加的按钮选中态可以让用户直观看到当前生效的字号基准,提升交互体验。

内容的提问来源于stack exchange,提问作者Snorlax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 08:24:16