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

如何用JavaScript和HTML实现可缩放段落字体的按钮?

字体放大缩小按钮实现方案

原代码问题分析

你的代码里有两个关键问题导致功能失效:

  1. 条件判断中"100 px"多了空格,实际设置的是"100px",两者不匹配,导致无法触发缩小逻辑
  2. 仅通过元素的内联style.fontSize获取字体大小,若样式来自CSS类而非内联,会获取不到有效值

修复基础版代码

先修正你的现有代码,让它能正常工作:

function biggerfont() {
  let bf = document.getElementById("font");
  let btn = document.getElementById('btn');

  // 修正空格问题,与设置的"100px"保持一致
  if (bf.style.fontSize === "25px") {
    bf.style.fontSize = "100px";
    btn.innerHTML = "Smaller";
  } else if (bf.style.fontSize === "100px") {
    bf.style.fontSize = "25px";
    btn.innerHTML = "Bigger";
  }
}
<p id="font" style="font-size: 25px;">Lorem Ipsum</p>
<button type="button" id="btn" onclick="biggerfont()">Bigger</button>

更灵活的动态缩放版本

如果需要支持逐步放大/缩小(而非仅切换两个固定值),可以用getComputedStyle获取当前实际字体大小,转换为数值后调整:

function toggleFontSize() {
  const textEl = document.getElementById("font");
  const btnEl = document.getElementById('btn');
  // 获取当前计算后的字体大小并转为数值
  const currentSize = parseFloat(window.getComputedStyle(textEl).fontSize);
  // 定义每次调整的步长
  const step = 10;

  if (btnEl.textContent === "Bigger") {
    textEl.style.fontSize = `${currentSize + step}px`;
    btnEl.textContent = "Smaller";
  } else {
    // 设置最小字体限制,避免缩得过小
    const newSize = Math.max(currentSize - step, 12);
    textEl.style.fontSize = `${newSize}px`;
    btnEl.textContent = "Bigger";
  }
}
<p id="font" style="font-size: 25px;">Lorem Ipsum</p>
<button type="button" id="btn" onclick="toggleFontSize()">Bigger</button>

这个版本支持每次点击按固定步长调整字体大小,还能限制最小字体,适用性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:10:28