实例
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>计算器</title> </head> <style> .box{ width:500px; border:1px solid #ccc; margin:20px auto; text-align:center; border-radius:5px; box-shadow:2px 2px 2px #ccc; background-color:#eee; } table{ margin:auto; } table tr td{ height:30px; } input{ width:100px; } button{ width:50px; height:20px; border:none; background:lightgreen; border-radius:5px; } button:hover{ cursor:pointer; background-color:coral; } </style> <body> <div class="box"> <form> <table> <caption>我的计算器</caption> <tr> <td><input type="text" placeholder="数字1" name="num1"></td> <td> <select> <option value="null">请选择</option> <option value="add">+</option> <option value="sub">-</option> <option value="mul">*</option> <option value="div">/</option> </select> </td> <td><input type="text" placeholder="数字2" name="num2"></td> <td><button type="button">计算</button></td> </tr> <tr> <td colspan="4" id="result">结果 </td> </tr> </table> </form> </div> <script> let num1 = document.getElementsByName('num1')[0]; let num2 = document.getElementsByName('num2')[0]; let type = document.getElementsByTagName('select')[0]; 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('数字1 不能为空'); num1.focus(); return false; }else if(isNaN(num1.value)){ //判断是否为数字 alert('数字1 必须是数字'); num1.focus(); return false; }else if(num2.value.length === 0){ alert('数字2 不能为空'); num2.focus(); return false; }else if (isNaN(num2.value)){ alert('数字2 必须是数字'); num2.focus(); return false; }else{ data1 = parseFloat(num1.value); //parseFloat() 函数可解析一个字符串,并返回一个浮点数。 data2 = parseFloat(num2.value); } let option = type.value; let flag = ''; let temp = 0; switch(option){ case 'null': alert('请选择运算符'); return false; break; 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('第二个除数不能为0'); num2.value = ''; num2.focus(); return false; }else{ temp = data1 / data2; temp = Math.round(temp*100)/100; //四舍五入结果保留两位小数 } break; } result.innerHTML = '<span style="color:orange;font-size:16px;">' + data1 + flag + data2 + '=' + temp + '</span>'; } </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例