计算器模拟
实例
<!DOCTYPE HTML> <html> <head> <meta http-equiv="content-type" content="text/html" charset="utf-8"/> <style> .comp{ width: 500px; min-height: 200px; box-shadow: 3px 3px 3px gray; margin: 0 auto; border: 1px solid #efefef; padding: 20px 100px; background: gray; border-radius: 5px; } #input1{ margin: 10px 0 ; } </style> <title>计算器模拟</title> </head> <body> <div class="comp"> <form> <input type="text" name="input1" id="input1" /> <select id="tag"> <option value="+">+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> </select> <input type="text" name="input2" id="input2" /> <button type="button" >计算</button> </form> <p >结果:</p> <p id="result"></p> </div> <script> //获取按钮 let btn = document.getElementsByTagName("button")[0]; let input1 = document.getElementById('input1'); let input2 = document.getElementById('input2'); let tags = document.getElementById('tag'); let p = document.getElementById('result'); btn.onclick = function (){ let num1 = 0; let num2 = 0; let tag = tags.value; result = 0; //非空判断/数据字符串解析处理 if(input1.value.length===0){ alert('第一个数不能为空'); input1.focus(); return false; }else if(isNaN(input1.value)){ alert('第一个数字符'); input1.focus(); return false; }else if(input2.value.length===0){ alert('第一个数不能为空'); input1.focus(); return false; }else if(isNaN(input2.value)){ alert('第一个数字符'); input1.focus(); return false; }else{ num1 = parseFloat(input1.value); num2 = parseFloat(input2.value); } //数据运算 if(tag==='+'){ result = num1+num2; }else if(tag==='-'){ result = num1-num2; }else if(tag==='*'){ result = num1*num2; }else{ if(num2===0) { alert('除数不能为0'); num2=''; return false; } result = num1/num2; } p.innerHTML= result; } </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例