本文实例为大家分享了JavaScript实现简单计算器的具体代码,供大家参考,具体内容如下

1.实现基本计算器功能,如图

2.逻辑代码

<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>计算器</title>
 <!--设置样式-->
 <style>
 .showdiv{
 text-align: center;
 margin:auto;/*设置居中*/
 border: solid 1px;
 width: 400px;
 height: 500px;
 border-radius: 10px;/*设置边框角度*/
 }
 input[type="text"]{
 margin-top: 10px;
 width: 380px;
 height: 40px;
 font-size: 40px;
 }
 input[type="button"]{
 margin: 10px;
 margin-top: 20px;
 width: 60px;
 height: 80px;
 font-size: 40px;
 font-weight: bold;
 }
 </style>
 <!--设置js代码-->
 <script type="text/javascript">
 /*将按钮的值赋值给输入框*/
 function num(btn){
 //把不能为零去掉
 if(document.getElementById("inp").value.match("除数")){
  document.getElementById("inp").value = "";
 }
 //获取button按钮的value
 var num = btn.value;
 console.log(num +" " +typeof(num))
 //将值赋值给text文本框
 switch(num){
  case "c":
  document.getElementById("inp").value = "";
  break;
  case "=":
  if(document.getElementById("inp").value.match("/")){
  if(document.getElementById("inp").value.split("/")[1] == "0"){
  document.getElementById("inp").value = "除数不能为零";
  }else{
  document.getElementById("inp").value = eval(document.getElementById("inp").value);
  }
  break;
  }else{
  document.getElementById("inp").value = eval(document.getElementById("inp").value);
  break;
  }
  default: 
  document.getElementById("inp").value = document.getElementById("inp").value+num;
  break;
 }
 }
 </script>
 </head>
 <body>
 <div class = "showdiv">
 <input type="text" name="" id="inp" value="" readonly="readonly"/><br />
 <input type="button" name="" id="" value="0" onclick="num(this)"/>
 <input type="button" name="" id="" value="1" onclick="num(this)"/>
 <input type="button" name="" id="" value="2" onclick="num(this)"/>
 <input type="button" name="" id="" value="3" onclick="num(this)"/><br />
 <input type="button" name="" id="" value="4" onclick="num(this)"/>
 <input type="button" name="" id="" value="5" onclick="num(this)"/>
 <input type="button" name="" id="" value="6" onclick="num(this)"/>
 <input type="button" name="" id="" value="7" onclick="num(this)"/><br />
 <input type="button" name="" id="" value="8" onclick="num(this)"/>
 <input type="button" name="" id="" value="9" onclick="num(this)"/>
 <input type="button" name="" id="" value="+" onclick="num(this)"/>
 <input type="button" name="" id="" value="-" onclick="num(this)"/><br />
 <input type="button" name="" id="" value="*" onclick="num(this)"/>
 <input type="button" name="" id="" value="/" onclick="num(this)"/>
 <input type="button" name="" id="" value="=" onclick="num(this)"/>
 <input type="button" name="" id="" value="c" onclick="num(this)"/>
 </div>
 </body>
</html>

赞(0) 踩(0)
发表我的评论

最新评论

  1. 暂无评论