<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算器</title> </head> <body> <div class="box"> <h2>小小计算器</h2> <form> <table> <tr> <td><input type="text" id="opt1" placeholder="操作数1" autofocus></td> <td> <select name="option" id="option"> <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" id="opt2" placeholder="操作数2"></td> <td><button type="button" id = "button">计算</button></td> </tr> <tr> <td colspan="2" align="right"><h3>结果:</h3></td> <td colspan="2" align="left"><h3 id="result"></h3></td> </tr> </table> </form> </div> <script type="text/javascript"> //1.获取元素 var opt1 = document.getElementById('opt1'); var opt2 = document.getElementById('opt2') var opt = document.getElementById('option'); var btn = document.getElementById('button'); var result = document.getElementById('result'); //2.给按钮添加事件,执行计算操作 btn.onclick = function(){ var data1 = 0; var 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); } var option = opt.value; var temp = 0; var 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('除数不能为0,请重新输入'); opt2.focus(); return false; } else { temp = data1 / data2; //保留小数点2位 temp = Math.round(temp * 100) / 100; } break } var str = '<span style="color:coral">'; str += data1+' '+flag+' '+data2 + ' = ' + temp ; str += '</span>'; result.innerHTML = str; } </script> </body> </html>