实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>calculator</title> <style type="text/css"> .box{ width: 400px;height: 400px; background-color: #E6E6E6; margin:50px auto; text-align: center; } table{ margin: 0 auto; } td {border: 1px solid E8E8E8;} input,select,button{width: 100%;height: 100%;border: none;} button:hover {background-color: coral;cursor: pointer;} </style> </head> <body> <div class="box"> <h1>计算器</h1> <form > <table> <tr> <td><input type="text" name="c1" placeholder="第一个数"></td> <td> <select name="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" name="c2" placeholder="第二个数"></td> <td><button type="button">计算</button></td> </tr> <tr> <td colspan="2"><h2>计算结果</h2></td> <td colspan="2"><h2 id="placeholder"></h2></td> </tr> </table> </form> </div> <script type="text/javascript"> var c1=document.getElementsByName('c1')[0] var c2=document.getElementsByName('c2')[0] var c=document.getElementsByName('option')[0] var btn =document.getElementsByTagName('button')[0] var placeholder=document.getElementById('placeholder') btn.onclick =function(){ if (c1.value.lenth==0){ alert('不能为空') c1.focus() return false } else if (isNaN(c1.value)){ alert('非数字') c1.focus() } else if (c2.value.lenth==0){ alert('不能为空') c2.focus() return false } else if (isNaN(c2.value)){ alert('非数字') c2.focus() } else { var data1 = parseFloat(c1.value) var data2 = parseFloat(c2.value) } var option =c.value var temp= 0 var flag =' ' var result = '' switch (option){ case 'Null': alert('请选择操作符') c.foucs() 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='/' temp= data1/data2 break } placeholder.innerHTML = '<span style="color:coral">'+data1+' '+ flag+' '+ data2+' = '+temp +'</span>' } placeholder.innerHTML = str </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例