簡體   English   中英

如何讓我的計算器在輸入數字前默認顯示“0”? 另外如何添加鍵盤輸入功能? 香草JS

[英]How to make my calculator default display show '0' before inputting a number? Also how to add keyboard input functionality? Vanilla JS

在將數字輸入計算器之前,我想將默認顯示值設為“0”。

我還想添加使用鍵盤輸入數字和操作的功能。

這是Codepen的鏈接

我嘗試將 this.currentOperand 的值更新為“0”,但沒有奏效。

我只能使用香草 JS

謝謝你看看。

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 rel="stylesheet" href="styles.css">
    <script src="script.js" defer></script>
</head>
<body>
    <div class="calculator-grid">
        <div class="output">
            <!-- Using the data attribute for js selection to save confusion with css if I used class -->
            <div data-previous-operand class="previous-operand"></div>
                <div data-current-operand class="current-operand"></div>
        </div>
        <button data-all-clear id='clear' class="span-two">AC</button>
        <button data-delete id='delete'>DEL</button>
        <button data-operation id='divide'>÷</button>
        <button data-number id='one'>1</button>
        <button data-number id='two'>2</button>
        <button data-number id='three'>3</button>
        <button data-operation id='multiply'>x</button>
        <button data-number id='four'>4</button>
        <button data-number id='five'>5</button>
        <button data-number id='six'>6</button>
        <button data-operation id='add'>+</button>
        <button data-number id='seven'>7</button>
        <button data-number id='eight'>8</button>
        <button data-number id='nine'>9</button>
        <button data-operation id='subtract'>-</button>
        <button data-number id='decimal'>.</button>
        <button data-number id='zero'>0</button>
        <button data-equals id='equals' class="span-two">=</button>
    </div>
    
</body>
</html>

Javascript

class Calculator {
    constructor( previousOperandTextElement, currentOperandTextElement){
        this.previousOperandTextElement = previousOperandTextElement;
        this.currentOperandTextElement = currentOperandTextElement;
        // Call the clear function to start with a clear display
        this.clear();
    }

    clear(){
        this.previousOperand = '';
        this.currentOperand = '';
        this.operation = '';

    }

    delete(){
        this.currentOperand = this.currentOperand.slice(0, -1)
        
        }

    

    appendNumber(number) {
        // If there is a '.' in the number and the currentOperand already contains a '.', end the function by returning. I.E do not append a '.'
        if (number === '.' && this.currentOperand.includes('.')) return;
        // Coverting the numbers to a string as JS will try to add the numbers together instead of appending ie putting onto the end
        this.currentOperand = this.currentOperand.toString() + number.toString();

    }

    chooseOperation(operation) {
        if (this.currentOperand === '') return;
        // This will compute the equation berofe appling another operation such as +, etc
        if (this.currentOperand !== ''){
            this.compute()
        }
        this.operation = operation;
        this.previousOperand = this.currentOperand;
        this.currentOperand = ''

    }

    compute() {
        let computation;
        // parseFloat() converts the string into a number, until it reaches a value that is not a number
        const prev = parseFloat(this.previousOperand);   
        const current = parseFloat(this.currentOperand);
        if (isNaN(prev) || isNaN(current)) return;
        // Switch statement for the calculation programming
        switch (this.operation) {
            case '+':
                computation = prev + current;
                break;
                case '-':
                    computation = prev - current;
                    break;
                    case 'x':
                computation = prev * current;
                break;
                case '÷':
                computation = prev / current;
                break;
                default:
                    return;
                
        }
        this.currentOperand = computation;
        this.operation = undefined;
        this.previousOperand = '';
    }

    updateDisplay() {
        // Displays text in the previous-operand div that is equal to currentOperand 
        this.currentOperandTextElement.innerText = this.currentOperand;
        if (this.operation != null){
        // Displays a concatenation of previous operand and the operation symbol
        this.previousOperandTextElement.innerText = `${this.previousOperand} ${this.operation}`;
    }
    }
}


// Data attribute needs to be inside []
const numberButtons = document.querySelectorAll('[data-number]');
const operationButtons = document.querySelectorAll('[data-operation]');
const deleteButton = document.querySelector('[data-delete]');
const equalsButton = document.querySelector('[data-equals]');
const allClearButton = document.querySelector('[data-all-clear]');
 
const previousOperandTextElement = document.querySelector('[data-previous-operand]');
const currentOperandTextElement = document.querySelector('[data-current-operand]');

// Defining a new Calculator class. Function declaration?
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();
})

CSS

*, *::before, *::after {
    box-sizing: border-box;
    font-family: Arial, Helvetica, sans-serif;
    font-weight: normal;
}

body {
    padding: 0;
    margin: 0;
    background: linear-gradient(to right, #7262B3, #CF98B6);

}

.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: solid 1px #CF98B6;
    /* border-radius: 10px; */
    outline: none;
    background-color: rgba(255,255,255, .75);
}

.calculator-grid > button:hover {
    background-color: rgba(255,255,255, .91);
}
/* This causes any button within the span-two class to span over two squares */
.span-two {
    grid-column: span 2;
}

.output {
    /* This spans the output from the 1st column (1) to the last column (-1) */
    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;    
}

我解決這個問題的方法是使用 if 語句將計算器重置為 0,然后在滿足 0 條件后將字符串設置為空。

if (this.currentOperand === '0') {
        this.currentOperand = '';
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM