实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算器</title> <style> body { background-color: #eee; } .box { margin: 50px 500px; padding: 10px; width: 500px; height: 300px; background-color: #fff; box-shadow: 0 0 20px 0 rgb(0,0,0,0.3); overflow: hidden; } .box h2 { text-align: center; line-height: 80px; color: #666; } .box input { padding: 5px 10px; width: 110px; margin-right: 2px; } .box select { padding: 5px 10px; } .box button { padding: 4px 8px; width: 80px; } .box .res { height: 70px; } .box .left { margin-left: 80px; } .box .right { padding: 0 10px; color: #fb6318; } </style> </head> <body> <div class="box"> <h2>计算器</h2> <form> <table> <tbody> <tr> <td> <input type="text" name="opt1" placeholder="操作数1"> </td> <td> <select name="option"> <option value="null">请选择操作符</option> <option value="0">请选择操作符</option> <option value="add">+</option> <option value="sub">-</option> <option value="mul">*</option> <option value="div">/</option> </select> </td> <td> <input type="text" name="opt2" placeholder="操作数2"> </td> <td> <button type="button">计算</button> </td> </tr> <tr> <td class="res" colspan="4"> <span class="left">计算结果:</span> <span class="right">1</span> </td> </tr> </tbody> </table> </form> </div> </body> <script> // 1.获取操作,按钮,结果占位符的值 let opt1=document.getElementsByName('opt1')[0]; let opt2=document.getElementsByName('opt2')[0]; let opt=document.getElementsByName('option')[0]; let btn=document.getElementsByTagName('button')[0]; let result=document.getElementsByClassName('right')[0]; // 2.给按钮添加事件,进行计算 btn.onclick=function () { //操作数初始化 let data1 = 0; let data2 = 0; if (opt1.value.length === 0) { alert('第一个操作数不能为空'); opt1.focus(); return false; } else if (isNaN(opt1.value)) { alert('第一个操作数必须为数字'); opt1.focus(); return false; } else if (opt2.value.length === 0) { alert('第二个操作数不能为空'); opt2.focus(); return false; } else if (isNaN(opt2.value)) { alert('第二个操作数必须为数字'); opt2.focus(); return false; } else { data1 = parseFloat(opt1.value); data2 = parseFloat(opt2.value); } //对操作符进行处理 let option = opt.value; let temp = 0; let flag = ''; switch (option) { case 'null': alert('请选择操作类型'); opt.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('除数不能为零'); opt2.focus(); opt2.value = ''; return false; } else { temp = data1 / data2; // 四舍五入保留二位小数 temp = Math.round(temp * 100) / 100; } break; } let str = ''; str += data1 + ' ' +flag + ' ' + data2 + ' = ' +temp; result.innerHTML = str; } </script> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例