如何居中输入框与按钮?如何实现HTML答题对错自动校验?
问题解决:输入框按钮整体居中 + 验证逻辑修复
问题分析
验证失败原因:
equations变量未全局声明,导致验证函数无法读取答案数据- 答案可能是1-4位数字,但输入框固定4个,直接取
equations[0]到equations[3]会在答案位数不足时得到undefined,导致拼接结果错误 - 未处理答案与输入框位数对齐的问题(比如答案是5,需要匹配4位输入
0005)
布局居中问题:
- 原CSS仅设置元素内部文本居中,未将输入框和按钮作为整体居中,需通过容器包裹实现块级居中
修改后的完整代码
HTML代码
<html> <head> <title>验证代码</title> <link href='style.css' rel='stylesheet'> <script> // 全局存储答案的字符数组 let equations = []; // 生成一元一次随机方程 function generateEquation() { var a = Math.floor(Math.random() * 10) + 1; var b = Math.floor(Math.random() * 10) + 1; var x = Math.floor(Math.random() * 10) + 1; var operator = Math.floor(Math.random() * 2); var equation = ""; switch (operator) { case 0: equation = a + "x + " + b + " = " + (a*x+b); break; case 1: equation = a + "x - " + b + " = " + (a*x-b); break; } return equation; } // 检查用户输入是否正确 function checkAnswer() { // 获取用户输入并拼接成字符串 let userInput = [ document.getElementById("input1").value, document.getElementById("input2").value, document.getElementById("input3").value, document.getElementById("input4").value ].join(''); // 将答案补前导零到4位,匹配输入框格式 let correctAnswer = equations.join('').padStart(4, '0'); if (userInput === correctAnswer) { document.getElementById("result").innerHTML = "验证成功!"; } else { document.getElementById("result").innerHTML = "验证失败,请重试。"; } } // 生成新方程并显示 function newEquation() { var equation = generateEquation(); var answer = eval(equation.split('=')[1]); equations = answer.toString().split(""); document.getElementById("equation").innerHTML = equation; // 清空输入框和结果提示 document.getElementById("input1").value = ""; document.getElementById("input2").value = ""; document.getElementById("input3").value = ""; document.getElementById("input4").value = ""; document.getElementById("result").innerHTML = ""; } </script> </head> <body> <h1>验证代码</h1> <p>请解出以下方程:</p> <p id="equation"></p> <!-- 用容器包裹输入框和按钮,实现整体居中 --> <div class="input-group"> <input type="text" id="input1" placeholder="X" size="2"> <input type="text" id="input2" placeholder="X" size="2"> <input type="text" id="input3" placeholder="X" size="2"> <input type="text" id="input4" placeholder="X" size="2"> <button onclick="checkAnswer()">提交</button> <button onclick="newEquation()">新方程</button> </div> <p id="result"></p> <script>newEquation()</script> </body> </html>
CSS代码
h1 { text-align: center; } p{ text-align: center; } /* 输入框按钮容器,实现整体居中 */ .input-group { text-align: center; margin: 1rem 0; } input { text-align: center; margin: 0 0.2rem; } button{ margin: 0 0.5rem; }
修改说明
验证逻辑修复:
- 声明全局
equations变量,确保验证函数能读取答案 - 将答案补前导零到4位,和输入框的4位格式统一(比如答案5转为
0005) - 优化输入获取方式,用数组拼接更简洁
- 声明全局
布局居中实现:
- 新增
input-group容器包裹输入框和按钮 - 给容器设置
text-align: center,让内部元素整体居中 - 给输入框和按钮添加margin,优化间距
- 新增
内容的提问来源于stack exchange,提问作者ziqian
相关产品推荐
相关产品推荐

