前端使用JavaScript实现一个简易计算器,没有难度,但是里面有些小知识

前端使用JavaScript实现一个简单的计算器,难度不大,但是有一些小知识需要注意。可以看作是基础知识复习。

话题

实现一个简化版的计算器,要求如下:

1、除法运算时,如果被除数为0,则结果为02、如果结果为小数,最多保留两位小数,如2 / 3 = 0.67 (display 0.67), 1 / 2 = 0.5(display0.5)3、请阅读并完成函数initEvent, result并根据提示计算4、请不要手动修改html和css5、不要使用第三方插件

完成

HTML 文件

<div class="calculator">
    <header class="cal-header">简易计算器header>
    <main class="cal-main">
        <div class="origin-value">0div>
        <div class="cal-keyboard">
            <ul class="cal-items">
                <li data-action="num">7li>
                <li data-action="num">8li>
                <li data-action="num">9li>
                <li data-action="operator">÷li>
                <li data-action="num">4li>
                <li data-action="num">5li>
                <li data-action="num">6li>
                <li data-action="operator">xli>
                <li data-action="num">1li>
                <li data-action="num">2li>
                <li data-action="num">3li>
                <li data-action="operator">-li>
                <li data-action="num">0li>
                <li data-action="operator">清空li>
                <li data-action="operator">=li>
                <li data-action="operator">+li>
            ul>
        div>
    main>
div>
复制代码

CSS 文件

body, ul, li,select {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
ul,li {list-style: none;}
.calculator {
    max-width: 300px;
    margin: 20px auto;
    border: 1px solid #eee;
    border-radius: 3px;
}
.cal-header {
    font-size: 16px;
    color: #333;
    font-weight: bold;
    height: 48px;
    line-height: 48px;
    border-bottom: 1px solid #eee;
    text-align: center;
}
.cal-main {
    font-size: 14px;
}
.cal-main .origin-value {
    padding: 15px;
    height: 40px;
    line-height: 40px;
    font-size: 20px;
    text-align: right;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
}
.cal-main .origin-type,
.cal-main .target-type {
    padding-left: 5px;
    width: 70px;
    font-size: 14px;
    height: 30px;
    border: 1px solid #eee;
    background-color: #fff;
    vertical-align: middle;
    margin-right: 10px;
    border-radius: 3px;
}
.cal-keyboard {
    overflow: hidden;
}
.cal-items {
    overflow: hidden;
}
.cal-items li {
    user-select: none;
    float: left;
    display: inline-block;
    width: 75px;
    height: 75px;
    text-align: center;
    line-height: 75px;
    border-top: 1px solid #eee;
    border-left: 1px solid #eee;
    box-sizing: border-box;
}
li:nth-of-type(4n+1) {
    border-left: none;
}
li[data-action=operator] {
    background: #f5923e;
    color: #fff;
}
.buttons {
    float: left;
    width: 75px;
}
.buttons .btn {
    width: 75px;
    background-color: #fff;
    border-top: 1px solid #eee;
    border-left: 1px solid #eee;
    height: 150px;
    line-height: 150px;
    text-align: center;
}
.btn-esc {
    color: #ff5a34;
}
.btn-backspace {
    position: relative;
}
复制代码

JavaScript 文件

var Calculator = {
    init: function () {
        var that = this;
        if (!that.isInited) {
            that.isInited = true;
            // 保存操作信息
            // total: Number, 总的结果
            // next: String, 下一个和 total 进行运算的数据
            // action: String, 操作符号
            that.data = {total: 0, next: '', action: ''};
            that.bindEvent();
        }
    },
    bindEvent: function () {
        var that = this;
        // 获取 .cal-keyboard 元素
        var keyboardEl = document.querySelector(".cal-keyboard");
        keyboardEl && keyboardEl.addEventListener('click', function (event) {
            // 获取当前点击的dom元素
            var target = event.target;
            // 获取target的 data-action 值
            var action = target.dataset.action;
            // 获取target的内容
            var value = target.innerText;
            if (action === 'num' || action === 'operator') {
                that.result(value, action === 'num');
            }
        });
    },
    result: function (action, isNum) {
        var that = this;
        var data = that.data;
        if (isNum) {
            data.next = data.next === '0' ? action : (data.next + action);
            !data.action && (data.total = 0);
        } else if (action === '清空') {
            // 设置清空时的对应状态
            data.total = 0;
            data.next = "";
            data.action = "";
        } else if (action === '=') {
            if (data.next || data.action) {
                data.total = that.calculate(data.total, data.next, data.action);
                data.next = '';
                data.action = '';
            }
        } else if (!data.next) {
            data.action = action;
        } else if (data.action) {
            data.total = that.calculate(data.total, data.next, data.action);
            data.next = '';
            data.action = action;
        } else {
            data.total = +data.next || 0;
            data.next = '';
            data.action = action;
        }
        // 获取 .origin-value 元素
        var valEl = document.querySelector(".origin-value");
        // print(data)
        valEl && (valEl.innerHTML = data.next || data.total || '0');
    },
    calculate: function (n1, n2, operator) {
        n1 = +n1 || 0;
        n2 = +n2 || 0;
        if (operator === '÷') {
            // 获取除法的结果
            return n2 === 0 ? 0 : Math.floor((n1 / n2) * 100) / 100;
        } else if (operator === 'x') {
            // 获取乘法的结果
            return Math.floor((n1 * n2) * 100) / 100;
        } else if (operator === '+') {
            // 获取加法的结果
            return Math.floor((n1 + n2) * 100) / 100;
        } else if (operator === '-') {
            // 获取减法的结果
            return Math.floor((n1 - n2) * 100) / 100;
        }
    }
};
Calculator.init();
复制代码

分析

主要分析本题JavaScript部分涉及的知识点。

事件委托

我们不是分别给number和symbol元素添加点击事件,而是给它们的父元素.cal-keyboard添加点击事件,然后通过事件冒泡获取绑定到其父元素的事件响应。使用事件委托具有以下优点:

事件委托的步骤:

绑定父元素响应事件c计算器代码简易版,监听子元素冒泡事件,获取触发事件的目标元素,保留小数位

大家的第一反应可能是使用 toFixed() 方法,但是当小数位数不足时,这个方法会在后面加 0,例如:

const num = 0.8;
num.toFixed(2) // 0.80
复制代码

如您所见,这不符合要求。

还有一个问题需要注意:小数相加的结果可能不符合预期,例如:

console.log(0.2 + 0.4) // 0.6000000000000001
复制代码

这里我们建议使用 Math.floor() 方法处理小数位c计算器代码简易版,先将结果乘以 100,然后使用 Math.floor() 得到整数部分,再除以 100 得到想要的结果,对于例子:

const num1 = 0.5;
const num2 = 0.68751;
Math.floor(num1 * 100)/100   	// 0.5
Math.floor(num2 * 100)/100		// 0.68
复制代码

~

~ 本文结束

~

学习有趣的知识,结识有趣的朋友,塑造有趣的灵魂!

大家好,我是〖Programming Samadhi〗作者王寅一。我的公众号是“编程三昧”。欢迎关注。希望大家多多指教!

你来了,满怀期待,我有墨香迎接你!你回来了,无论得到什么,失去什么,都只能带着回味送人!

知识与技能并重,内外兼修,理论与实践两手抓,双手要狠!

© 版权声明
THE END
喜欢就支持一下吧
点赞0
分享
评论 抢沙发

请登录后发表评论