freeCodeCamp 计算器小例子

Build a JavaScript Calculator
目标: 在 CodePen.io 上做一个类似于 http://codepen.io/FreeCodeCamp/full/zrRzMR 的 APP.
规则 #1: 代码是开源的,你可以借鉴,但请不要抄袭。
规则 #2: 可以使用你喜爱的任何库来定制属于你自己的风格,实现下面的功能.
功能: 可以对两个数字进行加、减、乘、除的运算.
功能: 可以使用清除按钮清空当前的所有输入内容.
功能: 可以把多个运算连接起来操作, 直到按下等号键, 计算器输出正确的运算结果.






    模仿计算机
    


    

freecodecamp calculator

/*style.css*/
@import url(https://fonts.googleapis.com/css?family=Oleo+Script);

html, body {
  height: 100%;
  width: 100%;
  background-color: #56351E;
}

h1 {
  font-family: 'Oleo Script', cursive;
  margin-top: 10px;
  color: #F19953;
}

button {
  height: 50px;
  border: none;
}

.calculator {
  text-align: center;
  width: 300px;
  height: 400px;
  border-radius: 10px;
  margin: auto;
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  background-color: #C47335;
  padding: 5px;
}

.buttons {
  width: 275px;
  text-align: center;
  margin:10px auto;
}

.button{
  float: left;
  margin: 2px;
  width: 64.75px;
  color: #f19953;
  background: #fff;
  cursor: pointer;
}

.textbox {
  margin-top: 10px;
  text-align: right;
  border: none;
  height: 25px;
  width: 275px;
  background-color: #F19953;
}
//common.js
var ans = "";   //存放计算之后的数值
var clear = false;  //存放是否清空的信号
var calc = "";  //存放当前输入计算机当中的值
$(document).ready(function() {
  $("button").click(function() {
    var text = $(this).attr("value");   //获取到点击的按钮的值
    //parseInt(text, 10)以10为基数进行解析
    if(parseInt(text, 10) == text || text === "." || text === "/" || text === "*" || text === "-" || text === "+" || text === "%") {
      if(clear === false) {
        calc += text;  //如果信号为不清空就连接字符串
        $(".textbox").val(calc);
      } else {    //如果信号为清空则新加入字符串
        calc = text;
        $(".textbox").val(calc);
        clear = false;
      }
    } else if(text === "AC") {
      calc = "";
      $(".textbox").val("");
    } else if(text === "CE") {
      calc = calc.slice(0, -1);
      $(".textbox").val(calc);
    } else if(text === "=") {
      try  {  //容错处理
         ans = eval(calc);   //eval() 函数可计算某个字符串,并执行其中的的 JavaScript 代码。
         }
      catch(exception) {
           alert("请输入正确的计算公式");
           }  
      $(".textbox").val(ans);
      clear = true;
    }
  });
});
freeCodeCamp 计算器小例子_第1张图片
模拟计算器.png

github地址:https://github.com/Iris-mao/css-tricks/tree/master/calculator

你可能感兴趣的:(freeCodeCamp 计算器小例子)