js计算器的实现
基本HTML结构
创建一个简单的HTML框架,包含显示屏和按钮区域。使用<div>和<button>元素构建界面,通过CSS进行基础样式设计。
<div class="calculator">
<div class="display">0</div>
<div class="buttons">
<button>7</button>
<button>8</button>
<button>9</button>
<button>+</button>
<!-- 其他按钮 -->
</div>
</div>
样式设计
通过CSS设置计算器的外观,包括按钮布局、颜色和显示屏样式。使用Flexbox或Grid布局确保按钮排列整齐。
.calculator {
width: 300px;
margin: 0 auto;
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
}
.display {
height: 50px;
background: #f4f4f4;
text-align: right;
font-size: 24px;
padding: 10px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 5px;
}
button {
height: 50px;
font-size: 18px;
}
JavaScript逻辑实现
通过事件监听捕获按钮点击,处理数字输入、运算符和计算逻辑。使用eval()或手动解析表达式实现运算功能。
const display = document.querySelector('.display');
const buttons = document.querySelectorAll('button');
let currentInput = '0';
let previousInput = '';
let operation = null;
buttons.forEach(button => {
button.addEventListener('click', () => {
const value = button.textContent;
if (value >= '0' && value <= '9') {
handleNumber(value);
} else if (value === '+' || value === '-' || value === '*' || value === '/') {
handleOperator(value);
} else if (value === '=') {
calculate();
} else if (value === 'C') {
clearAll();
}
updateDisplay();
});
});
function handleNumber(num) {
if (currentInput === '0') {
currentInput = num;
} else {
currentInput += num;
}
}
function handleOperator(op) {
if (operation !== null) calculate();
previousInput = currentInput;
currentInput = '0';
operation = op;
}
function calculate() {
let result;
const prev = parseFloat(previousInput);
const current = parseFloat(currentInput);
switch (operation) {
case '+':
result = prev + current;
break;
case '-':
result = prev - current;
break;
case '*':
result = prev * current;
break;
case '/':
result = prev / current;
break;
default:
return;
}
currentInput = result.toString();
operation = null;
previousInput = '';
}
function clearAll() {
currentInput = '0';
previousInput = '';
operation = null;
}
function updateDisplay() {
display.textContent = currentInput;
}
高级功能扩展
在基础功能上增加小数点处理、退格键功能和键盘支持。通过正则表达式验证输入,防止非法操作。
// 添加小数点处理
function handleDecimal() {
if (!currentInput.includes('.')) {
currentInput += '.';
}
}
// 添加键盘支持
document.addEventListener('keydown', (e) => {
if (e.key >= '0' && e.key <= '9') {
handleNumber(e.key);
} else if (e.key === '+' || e.key === '-' || e.key === '*' || e.key === '/') {
handleOperator(e.key);
} else if (e.key === 'Enter') {
calculate();
} else if (e.key === 'Escape') {
clearAll();
} else if (e.key === '.') {
handleDecimal();
}
updateDisplay();
});
错误处理与边界情况
增加除以零检查、输入限制和溢出处理。通过条件判断确保计算结果的合理性。
function calculate() {
let result;
const prev = parseFloat(previousInput);
const current = parseFloat(currentInput);
if (operation === '/' && current === 0) {
currentInput = 'Error';
operation = null;
previousInput = '';
return;
}
// 其他运算逻辑...
}
性能优化
使用事件委托替代单独按钮监听,减少内存占用。通过dataset属性存储操作类型,简化条件判断。
document.querySelector('.buttons').addEventListener('click', (e) => {
if (e.target.tagName === 'BUTTON') {
const action = e.target.dataset.action;
const value = e.target.textContent;
if (!action) {
handleNumber(value);
} else if (action === 'operator') {
handleOperator(value);
} else if (action === 'calculate') {
calculate();
} else if (action === 'clear') {
clearAll();
}
updateDisplay();
}
});






