The front-end uses JavaScript to implement a simple calculator, which is not difficult, but there are some small knowledge that should be paid attention to. It can be regarded as a review of basic knowledge.
subject
To realize a simple calculator, the requirements are as follows:
1. In the division operation, if the divisor is 0, the result is 0
2. If the result is decimal, two digits after the decimal point shall be reserved at most, such as 2 / 3 = 0.67 (0.67 is displayed), 1 / 2 = 0.5 (0.5 is displayed)
3. Please read and complete the functions initEvent, result and calculate according to the prompts
4. Please do not modify html and css manually
5. Do not use third-party plug-ins
realization
HTML file
<div class="calculator"> <header class="cal-header">Clean Calculator Beta </header> <main class="cal-main"> <div class="origin-value">0</div> <div class="cal-keyboard"> <ul class="cal-items"> <li data-action="num">7</li> <li data-action="num">8</li> <li data-action="num">9</li> <li data-action="operator">÷</li> <li data-action="num">4</li> <li data-action="num">5</li> <li data-action="num">6</li> <li data-action="operator">x</li> <li data-action="num">1</li> <li data-action="num">2</li> <li data-action="num">3</li> <li data-action="operator">-</li> <li data-action="num">0</li> <li data-action="operator">empty</li> <li data-action="operator">=</li> <li data-action="operator">+</li> </ul> </div> </main> </div>
CSS file
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 file
var Calculator = { init: function () { var that = this; if (!that.isInited) { that.isInited = true; // Save operation information // total: Number, total result // next: String, the next data to be calculated with total // action: String, operation symbol that.data = {total: 0, next: '', action: ''}; that.bindEvent(); } }, bindEvent: function () { var that = this; // obtain. Cal keyboard element var keyboardEl = document.querySelector(".cal-keyboard"); keyboardEl && keyboardEl.addEventListener('click', function (event) { // Gets the dom element currently clicked var target = event.target; // Get the data action value of target var action = target.dataset.action; // Get the content of 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 === 'empty') { // Set the corresponding status when emptying 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; } // obtain. Origin value element 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 === '÷') { // Get the result of division return n2 === 0 ? 0 : Math.floor((n1 / n2) * 100) / 100; } else if (operator === 'x') { // Get the result of multiplication return Math.floor((n1 * n2) * 100) / 100; } else if (operator === '+') { // Get the result of addition return Math.floor((n1 + n2) * 100) / 100; } else if (operator === '-') { // Get the result of subtraction return Math.floor((n1 - n2) * 100) / 100; } } }; Calculator.init();
analysis
Mainly analyze the knowledge points involved in the JavaScript part of this topic.
Event delegation
Instead of adding click events to numeric and symbolic elements, we add click events to their parent elements Cal keyboard adds a click event, and then obtains the event response bound by its parent element through event bubbling. Using event delegation has the following advantages:
- Reduce memory consumption
- You can easily add or delete elements dynamically
- Reduced number of managed functions
- Reduce the number of operations on DOM nodes and improve performance
Steps of event delegation:
- Bind response event to parent element
- Listen for bubbling events of child elements
- Gets the target element that triggers the event
Keep decimal places
Your first reaction may be to use the toFixed() method, but this method will fill in 0 when the decimal places are insufficient, for example:
const num = 0.8; num.toFixed(2) // 0.80
It can be seen that this does not meet the requirements.
There is another problem to note: the addition result of decimals may not meet expectations, such as:
console.log(0.2 + 0.4) // 0.6000000000000001
Here we recommend using math The floor () method is used to process decimal places. First multiply the result by 100, and then pass math Floor() gets the integer part, and then divides it by 100 to get a satisfactory result, such as:
const num1 = 0.5; const num2 = 0.68751; Math.floor(num1 * 100)/100 // 0.5 Math.floor(num2 * 100)/100 // 0.68
~
~End of this article
~
Learn interesting knowledge, make interesting friends and shape interesting souls!
Hello, I'm Programming samadhi Hermit Wang, my official account is " Programming samadhi "Welcome to pay attention and hope you can give us more advice!
You come, with expectations, I have ink to greet you! You return, no matter gain or loss, only with the rhyme!
Pay equal attention to knowledge and skills, cultivate both internal and external skills, grasp both theory and practice, and be hard on both hands!