-
Calculator 만들기) 3. Javascript 완성하기HTML & CSS & JAVASCRIPT 2021. 1. 22. 20:20
버튼의 전체적인 디자인을 완성했다면,
버튼 클릭시에 일어나는 계산과 화면상의 출력물을
javascript를 이용해서 설정한다.
1. 수식 버튼을 눌렀을 때 올바른 계산이 작동할 것
2. '.'을 누르거나 = 을 누르거나 ac, del 버튼 작동시 각각의 기능을 수행할 것
3. 화면상 보이는 숫자 3자릿 수 만다 ','가 찍히도록 숫자인식 방식을 줄 것
1. index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Calculator</title> <link href="styles.css" rel ="stylesheet"> <script src = "script.js" defer> </script> </head> <body> <div class = "calculator-grid"> <div class = "output"> <div data-previous-operand class = "previous-operand"></div> <div data-current-operand class="current-operand"></div> </div> <button data-all-clear class="span-two">AC</button> <button data-delete>DEL</button> <button data-operation>÷</button> <button data-number>1</button> <button data-number>2</button> <button data-number>3</button> <button data-operation>*</button> <button data-number>4</button> <button data-number>5</button> <button data-number>6</button> <button data-operation>+</button> <button data-number>7</button> <button data-number>8</button> <button data-number>9</button> <button data-operation>-</button> <button data-number>.</button> <button data-number>0</button> <button data-equals class="span-two">=</button> </div> </body> </html>
2. styles.css
*, *::before, *::after { box-sizing: border-box; font-family: Arial, sans-serif ; font-weight: normal; } body { padding: 0; margin: 0; background: linear-gradient(to right,#ffa585,#ffeda0); } .calculator-grid { display: grid; justify-content: center; align-content: center; min-height: 100vh; grid-template-columns: repeat(4, 100px); grid-template-rows: minmax(120px,auto) repeat(5,100px); } .calculator-grid > button { cursor: pointer; font-size: 2rem; border: 1px solid white; outline: none; background-color: rgba(255, 255, 255, .75); } .calculator-grid > button:hover { /*버튼 눌렀을 때*/ background-color: rgba(255, 255, 255, .9); } .span-two { grid-column: span 2; } .output { grid-column: 1 /-1; /*전체를 다 쓰도록 설정*/ background-color: rgba(0, 0, 0, .75); display: flex; align-items: flex-end; justify-content: space-around; /*양쪽 끝으로 이동해서 모양을 짓도록*/ flex-direction: column; /*수직한 모양으로 설정*/ padding: 10px; word-wrap: break-word; word-break: break-all; } .output .previous-operand { color:rgba(255, 255, 255, .75); font-size: 1.5rem; } .output .current-operand { color:white; font-size: 2.5rem; }
3. script.js
class Calculator{ constructor(previousOperandTextElement,currentOperandTextElement){ this.previousOperandTextElement = previousOperandTextElement this.currentOperandTextElement = currentOperandTextElement this.clear() } clear(){ /*AC 버튼 눌렀을 때*/ this.currentOperand = '' this.previousOperand = '' this.poreation = undefined } delete(){/*del 버튼 눌렀을 때*/ this.currentOperand = this.currentOperand.toString().slice(0, -1) /*한자리 삭제(가장 최근것을 삭제) */ } appendNumber(number){/* 숫자버튼 눌렀을 때*/ if(number === '.' && this.currentOperand.includes('.')) return this.currentOperand = this.currentOperand.toString() + number.toString() } chooseOperation(operation){ /* 수식기호 버튼 눌렀을 때*/ if(this.currentOperand ==='') return if(this.previousOperand !== ''){ this.compute() } this.operation = operation this.previousOperand = this.currentOperand this.currentOperand = '' } compute(){/* = 버튼 눌렀을 때*/ let computation const prev = parseFloat(this.previousOperand) const current = parseFloat(this.currentOperand) if(isNaN(prev)||isNaN(current)) return /*숫자가 아니면 계산하지 않는다. (빈칸인데 =누른다고 계산하지 않는다.) */ switch(this.operation){ case '+' : computation = prev + current break case '-' : computation = prev - current break case '*' : computation = prev * current break case '÷' : computation = prev / current break default : return } this.currentOperand = computation this.operation = undefined this.previousOperand = '' } getDisplayNumber(number){ /*숫자가 여러개 눌릴때 숫자를 어떻게 보일지 설정*/ const stringNumber = number.toString() const integerDigits = parseFloat(stringNumber.split('.')[0]) /* . 기준으로 앞에거 저장*/ const decimalDigits = stringNumber.split('.')[1] /* .기준으로 뒤의 것 저장 */ let integerDisplay if(isNaN(integerDigits)) {/*인티저자리는 en을 통해서 3자리마다 , 뜨도록 설정*/ integerDisplay = '' }else{ integerDisplay = integerDigits.toLocaleString('en',{ maximumFractionDigits: 0}) } if(decimalDigits !=null){/*소숫점자리는 ,붙지 않도록 설정*/ return `${integerDisplay}.${decimalDigits}` }else{ return integerDisplay } } updateDisplay(){/* 화면에 어떻게 보일 지 설정한다.*/ this.currentOperandTextElement.innerText = this.getDisplayNumber(this.currentOperand) if(this.operation != null) { /*수식기호가 있다면 계산한 값을 previousOperand에 보이도록 한다.*/ this.previousOperandTextElement.innerText = `${this.getDisplayNumber(this.previousOperand)} ${this.operation}` } else {/*없으면 current창만 뜨도록 설정 */ this.previousOperandTextElement.innerText = '' } } } const numberButtons = document.querySelectorAll('[data-number]') const operationButtons = document.querySelectorAll('[data-operation]') const equalsButton = document.querySelector('[data-equals]') const deleteButton = document.querySelector('[data-delete]') const allClearButton = document.querySelector('[data-all-clear]') const previousOperandTextElement = document.querySelector('[data-previous-operand]') const currentOperandTextElement = document.querySelector('[data-current-operand]') const calculator = new Calculator(previousOperandTextElement, currentOperandTextElement) numberButtons.forEach(button => { button.addEventListener('click', () => { calculator.appendNumber(button.innerText) calculator.updateDisplay() }) }) operationButtons.forEach(button => { button.addEventListener('click', () => { calculator.chooseOperation(button.innerText) calculator.updateDisplay() }) }) equalsButton.addEventListener('click', button => { calculator.compute() calculator.updateDisplay() }) allClearButton.addEventListener('click', button => { calculator.clear() calculator.updateDisplay() }) deleteButton.addEventListener('click', button => { calculator.delete() calculator.updateDisplay() })
사진으로 보면,
'HTML & CSS & JAVASCRIPT' 카테고리의 다른 글
Rock-Paper-Scissors 만들기) 2. Javascript 완성하기 (0) 2021.01.24 Rock-Paper-Scissors 만들기) 1. HTML, CSS 완성하기 (0) 2021.01.24 Calculator 만들기) 2. css 스타일 완성하기 (0) 2021.01.22 Calculator 만들기) 1. 기본 html, button 디자인 만들기 (0) 2021.01.21 Blooger Website) 8. 애니메이션 추가하기 (0) 2021.01.09