按下时“删除” /“退格”不触发我的功能

时间:2019-09-26 17:44:54

标签: javascript calculator addeventlistener keydown

我正在用JS构建计算器。除了删除键(删除最新输入的数字)外,我所有的按钮均有效。我曾尝试使用e.key =“ Backspace”和e.key =“ Delete”,但是当我使用事件侦听器并监听该按键时,应执行的函数未执行。

class Calculator {
  constructor(previousOperandTextElement, currentOperandTextElement) {
    this.previousOperandTextElement = previousOperandTextElement
    this.currentOperandTextElement = currentOperandTextElement
    this.clear()
  }

  clear() {
    this.currentOperand = ''
    this.previousOperand = ''
    this.operation = undefined
  }

  delete() {
    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

    // if (this.operation == '-' || this.operation == '–') {
    //   computation = prev + current
    // }
    if (this.operation == '+') {
      computation = prev + current
    }
    if (this.operation == '-' || this.operation == '–') {
      computation = prev - current
    }
    if (this.operation == 'x' || this.operation == '×') {
      computation = prev * current
    }
    if (this.operation == '/' || this.operation == '÷') {
      computation = prev / current
    }

    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)) {
      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) {
      this.previousOperandTextElement.innerText =
        `${this.getDisplayNumber(this.previousOperand)} ${this.operation}`
    } else {
      this.previousOperandTextElement.innerText = ''
    }
  }
}
const numberButtons = document.querySelectorAll('[data-number]')
const operationButtons = document.querySelectorAll('[data-operation]')
const equalsButton = document.querySelector('[data-equal]')
const deleteButton = document.querySelector('[data-delete]')
const allClearButton = document.querySelector('[data-clear]')
const previousOperandTextElement = document.querySelector('[data-previous]')
const currentOperandTextElement = document.querySelector('[data-current]')

const calculator = new Calculator(previousOperandTextElement, currentOperandTextElement)

//NUMBER BUTTONS
numberButtons.forEach(button => {
  button.addEventListener('click', () => {
    calculator.appendNumber(button.innerText)
    calculator.updateDisplay()
  })
})

window.addEventListener('keydown', e => {
  calculator.appendNumber(e.key)
  calculator.updateDisplay()
})

//OPERATION BUTTONS
operationButtons.forEach(button => {
  button.addEventListener('click', () => {
    calculator.chooseOperation(button.innerText)
    calculator.updateDisplay()
  })
})

window.addEventListener('keydown', e => {
  switch (e.key) {
    case '+':
      calculator.chooseOperation(e.key)
      calculator.updateDisplay()
      break;
    case '-':
      calculator.chooseOperation(e.key)
      calculator.updateDisplay()
      break;
    case 'x':
      calculator.chooseOperation(e.key)
      calculator.updateDisplay()
      break;
    case '/':
      e.preventDefault()
      calculator.chooseOperation(e.key)
      calculator.updateDisplay()
      break;
  }
})

//EQUAL BUTTON
equalsButton.addEventListener('click', button => compute())

window.addEventListener('keydown', e => {
  if (e.key == 'Enter') compute()
})

//CLEAR BUTTON
allClearButton.addEventListener('click', button => clear())

window.addEventListener('keydown', e => {
  if (e.key == 'c') clear()
})

//DELETE BUTTON
deleteButton.addEventListener('click', button => {
  calculator.delete()
  calculator.updateDisplay()
})

window.addEventListener('keydown', e => {
  if (e.key == 'Backspace') {
    console.log(e.key)
    calculator.updateDisplay()
  }
})


//REFACTOR
const clear = () => {
  calculator.clear()
  calculator.updateDisplay()
}
const compute = () => {
  calculator.compute()
  calculator.updateDisplay()
}
:root {
  --primary-dark: rgb(170, 172, 252);
  --primary-light: #f29191;
  --background: #eee; }

*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: inherit; }

html {
  box-sizing: border-box;
  font-size: 62.5%; }

body {
  font-family: sans-serif;
  background-color: var(--background);
  font-family: 'Noto Sans', sans-serif;
  font-weight: 400; }

button:focus,
input:focus {
  outline: none; }

.calculator {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: min-content repeat(6, 10rem);
  min-height: 60rem;
  max-width: 35rem;
  margin: 13vh auto 10rem auto;
  text-align: center;
  background: linear-gradient(135deg, var(--primary-dark), var(--primary-light));
  box-shadow: 0 2rem 4.5rem rgba(0, 0, 0, 0.2);
  border-radius: 1rem;
  overflow: hidden;
  opacity: 10%; }
  .calculator .btn:hover {
    box-shadow: 0 2rem 4.5rem rgba(88, 88, 88, 0.3); }
  .calculator .btn:active {
    box-shadow: 0 2rem 4.5rem rgba(88, 88, 88, 0.5);
    font-size: 2.8rem;
    transform: scale(0.95); }
  .calculator .btn:focus {
    outline: none;
    box-shadow: 0 2rem 4.5rem rgba(88, 88, 88, 0.3); }
  .calculator__mode {
    color: #fff;
    letter-spacing: 1px;
    padding-top: 1rem;
    font-weight: normal;
    font-size: 1.4rem;
    cursor: pointer;
    align-self: center;
    transition: all 0.4s cubic-bezier(0.075, 0.82, 0.165, 1);
    background-color: transparent;
    border: none;
    grid-row: 1/ span 1;
    grid-column: 1/span 1; }
    .calculator__mode:hover {
      transform: translateY(-3px); }
  .calculator__output {
    grid-column: 1/ -1;
    color: #fff;
    display: flex;
    align-items: flex-end;
    justify-content: space-around;
    flex-direction: column;
    padding: 10px;
    word-wrap: break-word;
    word-break: break-all; }
    .calculator__output--previous {
      color: rgba(255, 255, 255, 0.75);
      font-size: 1.5rem; }
    .calculator__output--current {
      color: white;
      font-size: 4rem; }
  .calculator .btn {
    color: #fff;
    font-size: 3rem;
    cursor: pointer;
    background-color: transparent;
    display: inline;
    border: none;
    border: 5px solid transparent;
    transition: all .1s; }
  .calculator__0 {
    grid-column: 2/ span 1;
    grid-row: 7/ span 1; }
  .calculator__1 {
    grid-column: 1/ span 1;
    grid-row: 6/ span 1; }
  .calculator__2 {
    grid-column: 2/ span 1;
    grid-row: 6/ span 1; }
  .calculator__3 {
    grid-column: 3/ span 1;
    grid-row: 6/ span 1; }
  .calculator__4 {
    grid-column: 1/ span 1;
    grid-row: 5/ span 1; }
  .calculator__5 {
    grid-column: 2/ span 1;
    grid-row: 5/ span 1; }
  .calculator__6 {
    grid-column: 3/ span 1;
    grid-row: 5/ span 1; }
  .calculator__7 {
    grid-column: 1/ span 1;
    grid-row: 4/ span 1; }
  .calculator__8 {
    grid-column: 2/ span 1;
    grid-row: 4/ span 1; }
  .calculator__9 {
    grid-column: 3/ span 1;
    grid-row: 4/ span 1; }
  .calculator__decimal {
    grid-column: 1/ span 1;
    grid-row: 7/ span 1; }
    .calculator__decimal span {
      margin-bottom: 1.1rem;
      display: block; }
  .calculator__delete {
    grid-column: 3/ span 1;
    grid-row: 7/ span 1; }
  .calculator__clear {
    grid-column: 4/ span 1;
    grid-row: 7/ span 1; }
  .calculator__equal {
    grid-column: 4/ span 1;
    grid-row: 4/span 3; }
  .calculator__plus {
    grid-column: 1/ span 1;
    grid-row: 3/ span 1; }
  .calculator__minus {
    grid-column: 2/ span 1;
    grid-row: 3/ span 1; }
  .calculator__divide {
    grid-column: 3/ span 1;
    grid-row: 3/ span 1; }
  .calculator__multiply {
    grid-column: 4/ span 1;
    grid-row: 3/span 1; }

footer {
  text-align: center;
  color: #757575; }
<!DOCTYPE html>
<html lang="en">

<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">

    <link href="https://fonts.googleapis.com/css?family=Noto+Sans:400,700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
    <title>Calculator</title>
</head>

<body>
    <div class="container">
        <div class="calculator">
            <button class="calculator__mode">Regular</button>

            <div class="calculator__output">
                <div data-previous class="calculator__output--previous"></div>
                <div data-current class="calculator__output--current"></div>
            </div>

            <button data-number class="btn calculator__0">0</button>
            <button data-number class="btn calculator__1">1</button>
            <button data-number class="btn calculator__2">2</button>
            <button data-number class="btn calculator__3">3</button>
            <button data-number class="btn calculator__4">4</button>
            <button data-number class="btn calculator__5">5</button>
            <button data-number class="btn calculator__6">6</button>
            <button data-number class="btn calculator__7">7</button>
            <button data-number class="btn calculator__8">8</button>
            <button data-number class="btn calculator__9">9</button>

            <button data-operation class="btn calculator__plus">+</button>
            <button data-operation class="btn calculator__minus">–</button>
            <button data-operation class="btn calculator__divide">÷</button>
            <button data-operation class="btn calculator__multiply">×</button>

            <button data-equal class="btn calculator__equal">=</button>


            <button data-number class="btn calculator__decimal"><span>.</span></button>
            <button data-clear class="btn calculator__clear">C</button>
            <button data-delete class="btn calculator__delete">DEL</button>

        </div>

        <footer>Designed & developed by Tyler Morales</footer>
    </div>

    <script src="scripts/app.js"></script>
</body>

</html>

0 个答案:

没有答案