实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <style type="text/css"> *{ margin: 0;padding: 0; } .box{ width: 600px; height: 300px; background-color: #ECECEC; margin: 30px auto; border-radius:30px ; box-shadow: 10px 10px 10px 5px #9C9C9C; text-align: center; } .main{ margin-top: 50px; } #inp1,#inp2,#acc{ width: 120px; height: 30px; border:1px solid coral; border-radius:5px ; } select{ border-radius:5px ; width: 110px; height: 30px; } #acc{ background-color: coral; } #acc:hover{ cursor: pointer; font-size: 1.2em; } .bottom{ margin-top: 50px; } .bottom h3,p{ text-align: center; } .bottom h3{ margin-bottom: 20px; } </style> <title>计算器的实战案例</title> </head> <body> <div class="box"> <h1>计算器</h1> <div class="main"> <form action="" method="post"> <input type="text" name="inp1" id="inp1" value="" /> <select name="option"> <option value="null">请输入操作符</option> <option value="add">加</option> <option value="sub">减</option> <option value="mul">乘</option> <option value="div">除</option> </select> <input type="text" name="inp2" id="inp2" value="" /> <input type="button" name="acc" id="acc" value="计算" /> </form> </div> <div class="bottom"> <h3>计算结果:</h3> <p id="results"></p> </div> </div> </body> </html> <script type="text/javascript"> var inp1 = document.getElementById("inp1") var inp2 =document.getElementById("inp2") var opt = document.getElementsByName('option')[0] var acc= document.getElementById("acc") var results = document.getElementById("results") acc.onclick = function(){ if(inp1.value.length==0){ alert('非法操作:第一选项不能为空') return false }else if(isNaN(inp1.value)){ alert('非法操作:第一选项不能为非数字') inp1.focus() return false }else if(inp2.value.length==0){ alert('非法操作:第2选项不能为空') return false }else if(isNaN(inp2.value)){ alert('非法操作:第2选项不能为非数字') inp1.focus() return false }else{ var data1 =parseFloat(inp1.value) var data2 =parseFloat(inp2.value) } var temp; var flag; switch(opt.value){ 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') inp2.focus() return false } else{ temp = data1 / data2 } break } //results.innerHTML = data1+flag+data2+'='+temp var str = '<span style="font-size:20px;color: coral;">' str += data1+flag+data2+'='+temp str += '</span>' results.innerHTML = str } </script>
运行实例 »
点击 "运行实例" 按钮查看在线实例