如何通过input标签实现HTML页面整体字体大小调整?
实现网页字体大小调整的修正方案
你的代码核心逻辑没问题,但存在两个关键问题导致功能失效:
- 输入框没有唯一标识,无法获取用户输入的数值
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
相关产品推荐
相关产品推荐

