繁体   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