Correction status:Uncorrected
Teacher's comments:
编程 : 使用js完成一个功能相对完整的计算器案例
div { width: 500px; height: 200px; background-color: lightblue; border: 1px solid grey; text-align: center; margin: auto; color: black; border-radius: 15px; box-shadow: 2px 2px 2px #999999; } table { margin: auto; } td { width: 100px; height: 30px; padding: 6px 6px; } input { width: 100%; height: 80%; border: none; text-align: left; margin-left: 15px; } select { width: 100%; margin-left: 12px; } button { width: 80%; height: 100%; border: none; background-color: lightcoral; color: white; margin-left: 5px; } button:hover { cursor: pointer; color: #000; background-color: coral; width: 90%; height: 110%; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="style.css"> <title>计算器实例</title> </head> <body> <div> <h2>简易计算器</h2> <form> <table> <tr> <td> <input type="text" name="sz1" placeholder="第一个数值"> </td> <td> <select name="xz" id=""> <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" name="sz2" placeholder="第二个数值"> </td> <td> <button type="button" name="button">计算</button> </td> </tr> <tr> <td align="right" colspan="2"><h3>结果:</h3></td> <td align="left" colspan="2"><h3 id="result"></h3></td> </tr> </table> </form> </div> <script> let sz1 = document .getElementsByName('sz1')[0]; let xz = document .getElementsByName('xz')[0]; let sz2 = document .getElementsByName('sz2')[0]; let but = document .getElementsByName('button')[0]; let result = document .getElementById('result'); but.onclick = function () { let data1 = 0; let data2 = 0; if (sz1.value.length === 0) { alert('第一个数值不能为空'); sz1.focus(); return false; } else if (isNaN(sz1.value)) { alert('第一个数值必须为数字'); sz1.focus(); return false; } else if (sz2.value.length === 0) { alert('第二个数值不能为空'); sz2.focus(); return false; } else if (isNaN(sz2.value)) { alert('第二个数值必须为数字'); sz2.focus(); return false; }else{ data1 = parseFloat(sz1.value); data2 = parseFloat(sz2.value); } let xz1 = xz.value; let temp = 0; let flag = ''; switch(xz1){ case 'null': alert('请选择运算符'); xz1.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('除数不能为零'); sz2.focus(); xz1.value = ''; return false; }else { temp = data1 / data2; temp = Math.round(temp * 100) / 100; } break; } let str = '<span style="color:coral">'; str += data1 + ' ' +flag + ' ' + data2 + ' = ' +temp; str += '</span>'; result.innerHTML = str; } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例
总结 : 最后的result的输出结果 , 还需要研究一下!!!