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

如何用原生JS实现字体大小最多增减两次的调整功能

解决方案:实现字体大小分步增减(最多两次,限0.5-1.5em)

原代码的问题在于每次点击直接设置固定字号,没有跟踪当前字体大小的状态,导致重复点击无法继续调整。通过维护当前字号变量并添加边界判断,即可实现需求:

完整代码实现

HTML

<button type="button" onclick="decreaseSize()" name="btn1">-A</button>
<button type="button" onclick="resetSize()" name="btn2">A</button>
<button type="button" onclick="increaseSize()" name="btn3">A+</button>
<hr />
<div id="container">
  <h1>This is the title</h1>
  <h2>This is a sub title</h2>
  <p>I need to increase the texts here by clicking on A+ button and decrease them by clicking -A button above. <br />
The problem here is that it increase/decrease only once. I want it to increase or decrease twice by say 25%. Not Thrice but just twice. How can I go about doing this?</p>
</div>

CSS

div {
  padding: 20px;
  border: 5px solid red;  
}
h1 {
  font-size: 2em;
}
h2 {
  font-size: 1.5em;
}
p {
  font-size: 1em;
}

JavaScript

const cont = document.getElementById("container");
// 初始化当前字号为默认值1em
let currentSize = 1;

function decreaseSize() {
  // 最小字号限制为0.5em,每次减少0.25em
  if (currentSize > 0.5) {
    currentSize -= 0.25;
    cont.style.fontSize = currentSize + "em";
  }
}

function increaseSize() {
  // 最大字号限制为1.5em,每次增加0.25em
  if (currentSize < 1.5) {
    currentSize += 0.25;
    cont.style.fontSize = currentSize + "em";
  }
}

function resetSize() {
  // 恢复默认字号
  currentSize = 1;
  cont.style.fontSize = currentSize + "em";
}

关键逻辑说明

  • 状态跟踪:用currentSize变量记录当前容器的字号,初始值为默认的1em。
  • 边界判断:
    • 点击-A时,仅当当前字号大于0.5em时继续缩小,确保最多点击两次(1→0.75→0.5)。
    • 点击A+时,仅当当前字号小于1.5em时继续放大,确保最多点击两次(1→1.25→1.5)。
  • 重置功能:点击A按钮直接恢复默认字号,同时重置状态变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 10:15:17