Javascript计算器(一)-基本功能实现

来源:互联网 发布:win10软件小助手 编辑:程序博客网 时间:2024/06/08 16:47

目标:JS计算器!
最终成品的样子
首先去看了关于DOM的内容,按照最基本的网页结构放了很多个button和一个input 进去

<input type="text" id="screen" name="screen" value="0"><br/><button type="button" id="1" onclick="input(this.innerHTML);">1</button><button type="button" id="2" onclick="input(this.innerHTML);">2</button><button type="button" id="3" onclick="input(this.innerHTML);">3</button><button type="button" onclick="BackS();">BackSpace</button><br/><button type="button" id="4" onclick="input(this.innerHTML);">4</button><button type="button" id="5" onclick="input(this.innerHTML);">5</button><button type="button" id="6" onclick="input(this.innerHTML);">6</button><br/><button type="button" id="7" onclick="input(this.innerHTML);">7</button><button type="button" id="8" onclick="input(this.innerHTML);">8</button><button type="button" id="9" onclick="input(this.innerHTML);">9</button><button type="button" id="10" onclick="input(10);">.</button><br/><button type="button" onclick="calc(this.innerHTML)">+</button><button type="button" onclick="calc(this.innerHTML)">-</button><button type="button" onclick="calc(this.innerHTML)">*</button><button type="button" onclick="calc(this.innerHTML)">/</button><button type="button" onclick="equal()">=</button><button type="button" id="clear" onclick="location.reload()">C</button><br/>

当然函数都是后来才写上然后添加进去的
基本思路就是 input 执行输入工作,每次让字符串附加一个

function input(str) {        if (document.getElementById("screen").value.toString()==="0")            document.getElementById("screen").value= null;        if (str===10) count ++;        if (count >= 2)        {            alert ("more dots are not available");            return 0;        }        document.getElementById("screen").value+=document.getElementById(str).innerHTML;    }

其中运用了DOM获取input框的对象,然后检测了是否为0,是否有超过两个小数点,这是最基本的检测
然后使用calc()函数来执行运算符号的添加,计算的核心就是用自带的eval()函数来计算表达式的值,所以思路就是把两次输入的数据合成成一串表达式字符串。

 function calc(cstr){        if (document.getElementById("screen").value !== null)            left=document.getElementById("screen").value+cstr;        //alert (left);        document.getElementById("screen").value="0";        count = 0;    }

其中的count也是用来规避小数点超出的情况的。
最后使用equal函数来完成最后的合成

  function equal() {        //alert(left);        var res_str=left+document.getElementById("screen").value;        var res_num=eval(res_str);        //alert(res_num);        document.getElementById("screen").value=res_num.toString();        count = 0;    }

思路非常简单,界面非常简单,功能也非常简单,纯粹是为了练习一下语言的运用。
之后会用一周的时间去进行美化,需要用CSS
最后附上完整源码

  <!DOCTYPE html>




Title



原创粉丝点击