本文實例為大家分享了js制作計算器的具體代碼,供大家參考,具體內容如下
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #show { width: 232px; height: 80px; color: white; border-radius: 5px 5px 0 0; background-color: rgba(127, 128, 127, 1); text-align: right; border: none; font-size: 45px; outline: none; } table { border: 1px solid black; border-collapse: collapse; width: 234px; text-align: center; font-size: 30px; } td { height: 55px; width: 57.5px; background-color: wheat; } td:active { background-color: coral; } .aperation { background-color: rgb(245, 146, 62); color: white; } #ape { background-color: wheat; color: #000000; } </style> </head> <body> <div id=""> <input type="" id="show" /> <table border="1"> <tr> <td id="clear">AC</td> <td>+/-</td> <td class="aperation" id="ape">%</td> <td class="aperation">/</td> </tr> <tr> <td class="num">7</td> <td class="num">8</td> <td class="num">9</td> <td class="aperation">*</td> </tr> <tr> <td class="num">4</td> <td class="num">5</td> <td class="num">6</td> <td class="aperation">-</td> </tr> <tr> <td class="num">1</td> <td class="num">2</td> <td class="num">3</td> <td class="aperation">+</td> </tr> <tr> <td colspan="2" class="num">0</td> <td>.</td> <td class="aperation" id="result">=</td> </tr> </table> </div> </body> <script type="text/javascript"> //獲取數字的集合 var nums = document.getElementsByClassName("num"); //獲取操作符的集合 var options = document.getElementsByClassName("aperation"); //獲取等號 var result = document.getElementById("result"); //獲取歸0 var clear = document.getElementById("clear"); //獲取展示框 var show = document.getElementById("show"); //聲明用於保存內容的三個變量 var numValue = ""; //存儲數字 var optionC = ""; //存儲操作符 var numTemp = ""; //存儲暫存值 //點擊數字鍵時 觸發事件 for(var i = 0; i < nums.length; i++) { nums[i].onclick = function() { if(numValue == "0") { numValue = ""; } numValue += this.innerHTML; show.value = numValue; } } //點擊操作鍵觸發事件 for(var i = 0; i < options.length - 1; i++) { options[i].onclick = function() { //先存儲之前記錄的數字 numTemp = numValue; //記錄操作符 optionC = this.innerHTML; //清除原有記錄的數字 numValue = ""; } } //等號操作 result.onclick = function() { show.value = eval(numTemp + optionC + numValue); } //清零操作 clear.onclick = function() { show.value = "0"; numValue = ""; optionC = ""; numTemp = ""; } </script> </html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。