以下代码实现简易计算器功能:
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算器</title> </head> <body> <div class="box"> <div class="input"> <input type="text" id="num1" name="num1" placeholder="请输入第一个数字"> <select id="cal" name="cal"> <option value="null">请选择操作</option> <option value="add">+</option> <option value="sub">-</option> <option value="mul">*</option> <option value="div">/</option> </select> <input type="text" id="num2" name="num2" placeholder="请输入第二个数字"> <button id="btn" name="btn">开始计算</button> </div> <div class="res"> <h4>计算结果:</h4> <h3 id="result" style="color: blue"></h3> </div> </div> <script> let num1=document.getElementById('num1'); let num2=document.getElementById('num2'); let cal=document.getElementById('cal'); let btn=document.getElementsByTagName('button')[0]; let result=document.getElementById('result'); btn.onclick=function () { let data1 = 0; let data2 = 0; if (num1.value.length === 0) { alert('第一个数不能为空'); num1.focus(); return false; } else if (isNaN(num1.value)) { alert('第一个数必须为数字'); num1.focus(); return false; } else if (num2.value.length === 0) { alert('第二个数不能为空'); num2.focus(); return false; } else if (isNaN(num2.value)) { alert('第二个数必须为数字'); num2.focus(); return false; } else { data1 = parseFloat(num1.value); data2 = parseFloat(num2.value); } let option = cal.value; let temp = 0; let flag = ''; switch (option) { case 'null': alert('请选择操作类型'); cal.focus(); return false; case 'add': flag = '+'; temp = data1 + data2; break; case 'sub': flag = '-'; temp = data1 - data2; break; case 'mul': flag = '*'; temp = data1 * data2; break; case 'div': flag = '/'; //进行除数不能为零的判断和处理 if (data2 === 0) { alert('除数不能为零'); num2.focus(); num2.value = ''; return false; } else { temp = data1 / data2; // 四舍五入,仅保留二位小数 temp = Math.round(temp * 100) / 100; } break; } let str = data1 + ' ' +flag + ' ' + data2 + ' = ' +temp; result.innerHTML = str; }; </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例