使用js完成一个功能相对完整的计算器案例
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算器</title> <style> .box{ width: 400px; height: 250px; background-color: #A6C8FF; border: 1px solid lightgrey; text-align: center; margin: 20px auto; color: #28a4c9; border-radius: 10px; box-shadow: 3px 3px 3px #9999CC; } table{ margin: auto; } td{ width: 100px; height: 30px; padding: 5px 10px; } input,select{ width: 100%; height: 100%; border: none; text-align: left; padding-left: 15px; } button{ width: 100%; height: 100%; border: none; background-color: #5cb85c; color: white; } button:hover{ cursor: pointer; background-color: #33CCFF; width: 110%; height: 110%; } </style> </head> <body> <div class="box"> <h3>计算器</h3> <form> <table> <tr> <td><input type="text" name="opt1" placeholder="输入框1"></td> <td> <select name="option" id=""> <option value="null">请填入数字</option> <option value="add">+</option> <option value="sub">-</option> <option value="mul">*</option> <option value="div">/</option> </select> </td> </tr> <tr> <td><input type="text" name="opt2" placeholder="输入框2"></td> <td><button type="button">计算</button></td> </tr> <tr> <td align="right"><h3>结果:</h3></td> <td align="left"><h3 id="result"></h3></td> </tr> </table> </form> </div> </body> </html> <script> 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.getElementById('result'); btn.onclick = function () { let data1 = 0; let data2 = 0; if (opt1.value.length === 0 ){ result.innerHTML = '第一个操作不能为空'; opt1.focus(); return false; }else if (isNaN(opt1.value)){ result.innerHTML = '第一个操作必须为数字'; opt1.focus(); return false; } else if (opt2.value.length ===0){ result.innerHTML = '第二个操作数不能为空'; opt2.focus(); return false; }else if (isNaN(opt2.value)){ result.innerHTML = '第二个操作数必须为数字'; 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': result.innerHTML = '请选择操作类型'; opt1.focus(); 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){ result.innerHTML = '除数不能为零'; opt2.focus(); opt2.value = ''; return false; }else { temp = data1/data2; temp = Math.round(temp *100) / 100; } break; } let str = '<span style="color: #2979ff">' str += data1 + ' ' +flag+' '+data2+ ' = ' + temp; str += '</span>'; result.innerHTML = str; } </script>
运行实例 »
点击 "运行实例" 按钮查看在线实例
总结,学完php,学js,感觉没那么难!