javascript - 如何让我的计算器在输入数字前默认显示“0”?另外如何添加键盘输入功能?香草JS
问题描述
在将数字输入计算器之前,我想将默认显示值设为“0”。
我还想添加使用键盘输入数字和操作的功能。
我尝试将 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 = '';
}
推荐阅读
- python - 获取列表中重复次数最多的元素重复的次数
- rust - Rust 反序列化:将字节向量转换为 uuid 的哈希集
- html - 简单的初学者问题:在下拉列表中随机启动选项?
- c# - C# - 对不止一个词使用自动完成
- google-data-studio - 尝试加载 repo 信息时,Github 连接器 Google Data Studio 抛出错误
- python - 在列表列表中转换 pd.DataFrame,同时为空文本“”替换“np.nan”值
- css - 在反应js中设置背景并模糊图像背景
- html - TailwindCSS - 修复了 flex 父级的 div 全宽
- excel - excel无法下载图片
- python - 简单的熊猫数据框转换