js实现计算器

在这里插入图片描述
在这里插入图片描述

<!DOCTYPE html>
<html lang="ch">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div{
            margin: 100px 0 0 300px;
        }
        div > p:nth-child(3) > input{
            display: inline-block;
            width: 60px;
        }
        div > p:nth-child(1){
            font: normal normal bold 12px/12px '微软雅黑';
            display: inline;
        }
        div > p:nth-child(1) > span:nth-of-type(2){
            font-size:36px;
        }
    </style>
</head>
<body>
    <div>
        <p>
            <input type="text" value="0">&nbsp;<span>+</span>&nbsp;
            <input type="text" value="0">&nbsp;=&nbsp;<span>0</span>
        </p>
        <p>
            <input type="button" value="+">
            <input type="button" value="-">
            <input type="button" value="*">
            <input type="button" value="/">
        </p>
        <p></p>
    </div>
</body>
<script>
    function Calculator(){
        this.init = {
            input_1: document.querySelector('div>p:nth-of-type(1)>input:nth-of-type(1)'),
            input_2: document.querySelector('div>p:nth-of-type(1)>input:nth-of-type(2)'),
            method: document.querySelector('div>p:nth-of-type(1)>span:nth-of-type(1)'),
            result: document.querySelector('div>p:nth-of-type(1)>span:nth-of-type(2)'),
            add: document.querySelector('div>p:nth-of-type(2)>input:nth-of-type(1)'),
            substract: document.querySelector('div>p:nth-of-type(2)>input:nth-of-type(2)'),
            multiply: document.querySelector('div>p:nth-of-type(2)>input:nth-of-type(3)'),
            divide: document.querySelector('div>p:nth-of-type(2)>input:nth-of-type(4)'),
            history: document.querySelector('div>p:nth-of-type(3)'),
            _info: function(){
                let input_1_value = this.input_1.value;
                let input_2_value = this.input_2.value;
                return [input_1_value, input_2_value];
            },
            addFun: function(){
                let argu = this._info();
                let res =  +argu[0] + +argu[1];
                this.display('+', res);
            },
            substractFun: function(){
                let argu = this._info();
                let res =  +argu[0] - +argu[1];
                this.display('-', res);
            },
            multiplyFun: function(){
                let argu = this._info();
                let res =  +argu[0] * +argu[1];  
                this.display('*', res);
            },
            divideFun: function(){
                let argu = this._info();
                let res =  +argu[0] / +argu[1];
                this.display('/', res);
            },
            display: function(method, res){
                this.method.innerHTML = method;
                this.result.innerHTML = res;
            }
        };
        function formatInput(_this, string, myself){
            let newStr = '', bool = false;
            myself.removeAttribute('style');
            for(let i of string){
                // 判断字符串是否含有除 数字、小数点 以外的字符
                let pattern_1 = /\d/g,
                    pattern_2 = /\./g;
                if(!(pattern_1.test(i) || pattern_2.test(i))){
                    myself.setAttribute('style', 'border: 2px solid red;');
                };
                // 删除多余的00, 000123 ==> 123
                if(newStr.length===0 && i==='0'){
                    continue;
                };
                // 保留第一个小数点, 1.2.3.4 ==> 1.234
                if(i === '.' && bool === false){
                    bool = true;
                    newStr += i;
                }else if(i === '.' && bool === true){
                    continue;
                }else{
                    newStr += i;
                };
            };
            // 删除多余小数点, 123. ==> 123
            if(newStr[newStr.length-1] === '.'){
                newStr = newStr.slice(0, newStr.length-1);
            };
            // 添加0, .123 ==> 0.123
            if(newStr[0] === '.'){
                newStr = '0' + newStr;
            };
            return +newStr
        }
        function addEvents(_this){
            _this.init.input_1.addEventListener('blur', function(event){
                event.target.value = formatInput(_this, event.target.value, this);
            });
            _this.init.input_2.addEventListener('blur', function(event){
                event.target.value = formatInput(_this, event.target.value, this);
            });
            _this.init.add.addEventListener('click', function(){
                _this.init.addFun();
            });
            _this.init.substract.addEventListener('click', function(){
                _this.init.substractFun();
            });
            _this.init.multiply.addEventListener('click', function(){
                _this.init.multiplyFun();
            });
            _this.init.divide.addEventListener('click', function(){
                _this.init.divideFun();
            });
        };
        addEvents(this);
    };
    Calculator.prototype.addButton = function(name){
        var target = document.querySelector('div>p:nth-of-type(2)');
        var newButton = document.createElement('input');
        newButton.setAttribute('type', 'button');
        newButton.setAttribute('value', name);
        target.appendChild(newButton);
        return newButton;
    };
    Calculator.prototype.addMethod = function(name, callback){
        let newButton = this.addButton(name);
        newButton.addEventListener('click', callback);
        return newButton;
    };
    Calculator.prototype.addHistory = function(content){
        let history = cal.init.history.innerHTML,
            myDate = new Date(),
            currentTime = myDate.toLocaleTimeString(),
            newHistory = history + currentTime + ': ' + content + ';<br/>';
        cal.init.history.innerHTML = newHistory;
    };
    // ===== ===== ===== ===== =====
    // ===== ===== ***** ===== =====
	// ===== ===== ===== ===== =====
    var cal = new Calculator();
    cal.addMethod('power', function(){
        cal.init.display('^', Math.pow(cal.init.input_1.value, cal.init.input_2.value));
    });
    cal.addMethod('clear', function(){
        cal.init.display('+', 'None');
        cal.init.input_1.value = '';
        cal.init.input_2.value = '';
    });
    cal.addMethod('colorON', function(){
        cal.init.result.setAttribute('style', 'color: red;font-size:40px;');
        cal.init.history.setAttribute('style', 'color: red;font-size:24px;width:800px;');
    })
    cal.addMethod('colorOFF', function(){
        cal.init.result.setAttribute('style', 'font-size:36px;');
        cal.init.history.setAttribute('style', 'font-size:20px;');
    });
    cal.addMethod('save', function(){
        let input_1 = cal.init.input_1.value || 'None',
            input_2 = cal.init.input_2.value || 'None',
            method = cal.init.method.innerHTML,
            result = cal.init.result.innerHTML,
            content = input_1 + ' ' + method + ' ' + input_2 + ' = ' + result;
        cal.addHistory(content);
    });
    // 此方法旨在修改error: 0.1 + 0.2 = 0.30000000000000004
    var amendBtn = cal.addMethod('amend', function(){
        function acquire_extendArgu(input_1, input_2){
            if(input_1.indexOf('.') === -1 && input_2.indexOf('.') === -1) return ;
            let slice_1 = input_1.slice(input_1.indexOf('.')+1, input_1.length),
                slice_2 = input_2.slice(input_2.indexOf('.')+1, input_2.length),
                res = slice_1 >= slice_2 ? slice_1.length : slice_2.length;
            return Math.pow(10, +res);
        }
        let res = acquire_extendArgu(cal.init.input_1.value, cal.init.input_2.value);
        cal.init.addFun = function(){
            let argu = this._info(),
                newRes =  +argu[0]*res + +argu[1]*res;
            this.display('+', newRes/res);
        };
        cal.addHistory('已经手动修复加法(0.1+0.2=0.3)');
        cal.init.add.setAttribute('style', 'color: red;');
        cal.init.method.setAttribute('style', 'color: red;');
        cal.init.method.setAttribute('style', 'color: red;');
    })
    amendBtn.setAttribute('title', '此方法旨在修改error: 0.1 + 0.2 = 0.30000000000000004');
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值