全国统一服务热线:400-633-9193

JavaScript实现一个简易的计算器实例代码

    网络     2018-06-01    1490

自己期末复习的时候就一直想要写一个计算器,闲暇的时候也在想具体怎么实现,觉得应该不难,但就是想写。昨天终于可以开始动工,刚开始还以为实现出来需要一个周左右至少两天的时间,想着实现完我就可以先回家两天了。但没想到整个实现过程算比较顺利吧,昨天用了大概六个小时完成了从设计到具体实现。 

有大概一个月没怎么写代码了,整个大脑都不适应,反应也慢,一些基本的东西都有点模糊不清了。可能是原来就没有太理解,再加上没有其余练习,导致效率有些低。

正文

html代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<div class="errorHint" id="errorHint"><img src="https://github.com/crystalYY/calculator/blob/master/img/error.png?raw=true"></div>
    <table cellpadding="0">
        <tr>
            <th colspan="5">计算器</th>
        </tr>
        <tr>
            <td colspan="5">
                <input type="text" value="0" name="showResult">
            </td>
        </tr>
        <tr>
            <td><button>7</button></td>
            <td><button>8</button></td>
            <td><button>9</button></td>
            <td><button class="setChange" id="backSpace">退格</button></td>
            <td><button class="setChange" id="clearNum">C</button></td>
        </tr>
        <tr>
            <td><button>4</button></td>
            <td><button>5</button></td>
            <td><button>6</button></td>
            <td><button>+</button></td>
            <td><button>-</button></td>
        </tr>
        <tr>
            <td><button>1</button></td>
            <td><button>2</button></td>
            <td><button>3</button></td>
            <td><button>*</button></td>
            <td><button>/</button></td>
        </tr>
        <tr>
            <td><button>0</button></td>
            <td><button>.</button></td>
            <td><button>%</button></td>
            <td colspan="2"><button class="setChange" id="gainResult">Enter</button></td>
        </tr>
    </table>
    <script type="text/javascript" src='index.js'>       
    </script>

 CSS代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
*{margin: 0px; padding: 0px;}
        .errorHint{position: absolute; left: 130px; top:-282px;}
        .showError{border:1px solid red;}
        table{ border: 2px solid #996c33; width: 550px; padding: 10px; margin: 150px auto; background:url(https://github.com/crystalYY/calculator/blob/master/img/bg2.jpg?raw=trueg) left center no-repeat; border-radius: 10px;}
        table td{
            text-align: center;
            width: 100px;
            height: 40px;
            padding-left: 2px;
            padding-bottom: 2px;
        }
        table th{
            font-size: 18px;
            font-family:'楷体';
            color:  #8B0000;
        }
        table td button{
            width: 98%;
            height: 98%;
            font-size: 16px;
            font-family: 'Microsoft yahei';
            background: none;
            color:  #8B4726;
            outline:none;
            border:1px solid #000;
            border-radius: 5px;
            cursor: pointer;
        }
        table td input{
            width: 100%;
            margin: 10px 0;
            padding: 5px;
            border:1px solid #996c33;
            box-sizing: border-box;                    
            text-align: right;
            font-size: 16px;
            font-family: 'Microsoft yahei';
        }

JS代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
var oinput=document.getElementsByTagName('input')[0];
        //获取外部样式
        function getStyle(obj, name)
        {
            if(obj.currentStyle)
            {
                return obj.currentStyle[name];
            }
            else
            {
                return getComputedStyle(obj, false)[name];
            }
        }
        //渐变动画
        function move(obj,attr,tar){
            clearInterval(obj.timer);
            obj.timer=setInterval(function(){
                var cur=parseInt(getStyle(obj,attr));
                var itarget=parseInt(tar);
                var speed=(itarget-cur)/6;
                speed=speed>0?Math.ceil(speed):Math.floor(speed);
                obj.style[attr]=parseInt(getStyle(obj,attr))+speed+'px';
                if(speed==0){
                    clearInterval(obj.timer);
                }
            },30);
        }
        //事件绑定函数
        function addEvent(obj,ev,fun){
            if(obj.attachEvent){
                obj.attachEvent('on'+ev,fun);
            }else{
                obj.addEventListener(ev,fun,false);
            }
        }
        //阻止默认行为
        function stopEvent(ev){
            var e=ev||window.event;
            if(e.preventDefault){
                e.preventDefault();
            }
            else{
                e.returnValue=false;//ie
            }
        }
        //计算最终结果
        function getResult(){
            function evalResult(){
                var result=eval(oinput.value);
                return result;         
            }
            //捕获异常
            try{
                var x=evalResult();
                return x;
            }
            catch (e){
                oinput.className='showError';
                var errorHint=document.getElementById('errorHint');
                move(errorHint,'top',0);
                setTimeout(function(){
                    oinput.className='';
                    move(errorHint,'top',-282);
                },2000);
                return oinput.value;
            }
        }
        //文本框获取焦点,错误提示消失
        //按下回车得到结果
        function enterResult(ev){
            var e=ev||window.event;
            if(e.keyCode==13){
                stopEvent(ev);//阻止enter键的默认行为
                var result=getResult();
                oinput.value=result;
            }
        }
        //绑定点击事件
        function init(){
            var otable=document.getElementsByTagName('table')[0];
            addEvent(otable,'keydown',function(ev){
                enterResult(ev);
            });
            addEvent(otable,'click',function(ev){
                stopEvent(ev);
                var e=ev||window.event;
                var itat=e.target||e.srcElement;
                var obtns=document.getElementsByTagName('button');
                if(itat.nodeName.toLowerCase()=='button'){
                    for(var i=0;i<obtns.length;i++){
                        obtns[i].style.borderColor='#000';
                    }
                    itat.style.borderColor='white';
                    if(itat.className!='setChange'){
                        if(oinput.value=='0'){
                            oinput.value='';
                            oinput.value+=itat.innerHTML;
                        }
                        else{
                            oinput.value+=itat.innerHTML;
                        }
                    }else{
                        if(itat.id=='backSpace'){
                            oinput.value=oinput.value.toString().slice(0,-1);
                        }
                        else if(itat.id=='clearNum'){
                            oinput.value='0';
                        }else{
                            var result=getResult();
                            oinput.value=result;
                        }
                    }
                }
            });
        }
        init();

正常显示界面 

错误提示界面 


  分享到:  
0.2078s