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

如何通过input标签实现HTML页面整体字体大小调整?

实现网页字体大小调整的修正方案

你的代码核心逻辑没问题,但存在两个关键问题导致功能失效:

  1. 输入框没有唯一标识,无法获取用户输入的数值
  2. onclick事件中使用的myFontSize是未定义变量,无法传递正确的参数

以下是修正后的完整代码:

HTML 部分

<form title="Change the Size of the Text!">
  <input type="number" id="fontSizeInput" placeholder="输入字体大小(px)" min="1">
  <input type="button" onclick="changeFontSize()" value="Give it in!">
</form>

JavaScript 部分

function changeFontSize() {
  // 获取输入框元素
  const sizeInput = document.getElementById('fontSizeInput');
  // 获取输入的数值
  const fontSize = sizeInput.value;

  // 验证输入是否为有效正整数
  if (!isNaN(fontSize) && fontSize > 0) {
    // 给body设置字体大小
    document.body.style.fontSize = `${fontSize}px`;
  } else {
    // 提示用户输入有效数值
    alert('请输入大于0的有效数字');
  }
}

关键修改说明

  • 给输入框添加id="fontSizeInput",让JS能精准获取输入元素
  • 移除按钮onclick中的无效参数,改为在函数内部获取输入值,逻辑更清晰
  • 增加输入验证,避免非数字、负数等无效值导致样式异常
  • 给输入框添加placeholder和min属性,提升用户输入体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:50:51