首页 > 编程 > JavaScript > 正文

JS键盘版计算器的制作方法

2019-11-19 18:41:07
字体:
来源:转载
供稿:网友

本文实例为大家分享了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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表