jquery计算器(改良版)
代码:
1 <!Doctype html> 2 <html> 3 <meta charset="UTF-8"> 4 <title>计算器</title> 5 <script src="jquery.min.js"></script> 6 <style> 7 button{ 8 9 width:80px; 10 height:50px; 11 background-color:#969696; 12 color:white; 13 font-size:17px; 14 } 15 </style> 16 <body> 17 <table> 18 <tr> 19 <td colspan="4" style="text-align:center;"> 20 <input type="text" value="0" style="font-size:17px;text-align:right;width:330px;height:50px;"> 21 </td> 22 </tr> 23 <tr> 24 <td> 25 <button class="num">7</button> 26 </td> 27 <td> 28 <button class="num">8</button> 29 </td> 30 <td> 31 <button class="num">9</button> 32 </td> 33 <td> 34 <button class="operator">+</button> 35 </td> 36 </tr> 37 <tr> 38 <td> 39 <button class="num">4</button> 40 </td> 41 <td> 42 <button class="num">5</button> 43 </td> 44 <td> 45 <button class="num">6</button> 46 </td> 47 <td> 48 <button class="operator">-</button> 49 </td> 50 </tr> 51 <tr> 52 <td> 53 <button class="num">1</button> 54 </td> 55 <td> 56 <button class="num">2</button> 57 </td> 58 <td> 59 <button class="num">3</button> 60 </td> 61 <td> 62 <button class="operator">*</button> 63 </td> 64 </tr> 65 <tr> 66 <td> 67 <button class="num">0</button> 68 </td> 69 <td> 70 <button id="point">.</button> 71 </td> 72 <td> 73 <button id="eq">=</button> 74 </td> 75 <td> 76 <button class="operator">/</button> 77 </td> 78 </tr> 79 <tr> 80 <td> 81 <button id="clean">C</button> 82 </td> 83 </tr> 84 </table> 85 </body> 86 </html> 87 <script> 88 var status = 0; 89 var operat; 90 var firstnum; 91 var secondnum; 92 $("#clean").click(function(){ 93 status = 0; 94 $("input").val(0); 95 firstnum = 0; 96 secondnum = 0; 97 }) 98 $(".num").click(function(){ 99 if(status == 0){ 100 if($("input").val()==='0'){ 101 $("input").val($(this).html()); 102 }else if($("input").val() == '0.'){ 103 $("input").val('0.' + $(this).html()); 104 }else{ 105 $("input").val($("input").val() + $(this).html()); 106 } 107 firstnum = $("input").val(); 108 }else{ 109 if($("input").val() == '0.'){ 110 $("input").val('0.' + $(this).html()); 111 secondnum = $("input").val(); 112 }else{ 113 $("input").val($(this).html()); 114 secondnum = $("input").val(); 115 } 116 } 117 }) 118 $(".operator").click(function(){ 119 status = 1; 120 operat = $(this).html(); 121 }) 122 $("#point").click(function(){ 123 124 $("input").val($("input").val() + $(this).html()); 125 }) 126 $("#eq").click(function(){ 127 128 if(operat == '+'){ 129 $("input").val((parseFloat(firstnum)*10+parseFloat(secondnum)*10)/10); 130 }else if(operat == '-'){ 131 $("input").val((parseFloat(firstnum)*10-parseFloat(secondnum)*10)/10); 132 }else if(operat == '*'){ 133 $("input").val((parseFloat(firstnum)*10*parseFloat(secondnum)*10)/100); 134 }else{ 135 $("input").val((parseFloat(firstnum)*10/parseFloat(secondnum)*10)/100); 136 } 137 firstnum = $("input").val(); 138 status = 0; 139 }) 140 </script>
效果图: