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

如何用JavaScript实现点击按钮每次将textarea字体大小增加2px

问题原因

  • 你通过 HTMLElement.style.fontSize 只能读取到元素行内 style 属性中显式声明的字体大小,默认textarea没有设置行内字号,第一次读取会拿到空字符串,parseInt("") 结果为NaN,后续计算全部失效。
  • 给fontSize赋值时没有加单位px,纯数字无法被浏览器识别为合法的字体大小值,样式不会生效。

修正方案

方法1(兼容性最优,无需改HTML)

通过getComputedStyle读取元素实际渲染的字号,兼容行内样式、样式表定义的字号,赋值时补充px单位即可:

function makebold() {
  const textEl = document.getElementById("input-text");
  // 读取实际生效的字体大小
  const currentFontSize = window.getComputedStyle(textEl).fontSize;
  const current = parseInt(currentFontSize);
  const updatedFontSize = current + 2;
  // 赋值时补充px单位
  textEl.style.fontSize = `${updatedFontSize}px`;
}

方法2(最小改动原有代码)

直接给textarea加行内样式预设初始字号,原有JS只要补px单位即可运行:

<!-- 修改textarea标签,加初始行内字号 -->
<textarea name="input-text" id="input-text" cols="30" rows="4" style="font-size: 16px"></textarea>

修改JS最后一行赋值逻辑:

document.getElementById("input-text").style.fontSize = newfont + 'px';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:09:03