js制作一个简易计算器
时间: 2024-05-07 11:18:26 浏览: 128
A-simple-Calculator-master_html_javascript_calculator_css_
好的,下面是一个简单的HTML/CSS/JavaScript计算器示例:
HTML:
```html
<div class="calculator">
<input type="text" class="display" disabled>
<div class="keys">
<button class="operator" value="+">+</button>
<button class="operator" value="-">-</button>
<button class="operator" value="*">×</button>
<button class="operator" value="/">÷</button>
<button value="7">7</button>
<button value="8">8</button>
<button value="9">9</button>
<button value="4">4</button>
<button value="5">5</button>
<button value="6">6</button>
<button value="1">1</button>
<button value="2">2</button>
<button value="3">3</button>
<button value="0">0</button>
<button value=".">.</button>
<button class="clear" value="clear">C</button>
<button class="calculate" value="=">=</button>
</div>
</div>
```
CSS:
```css
.calculator {
width: 200px;
margin: 0 auto;
padding: 20px;
background-color: #f1f1f1;
border-radius: 10px;
text-align: center;
}
.display {
width: 100%;
height: 50px;
font-size: 24px;
text-align: right;
margin-bottom: 10px;
padding: 5px;
}
.keys button {
width: 50px;
height: 50px;
margin: 5px;
font-size: 24px;
border: none;
border-radius: 5px;
background-color: #e0e0e0;
cursor: pointer;
outline: none;
}
.keys button:hover {
background-color: #d0d0d0;
}
.keys button.operator {
background-color: #f0a0a0;
color: white;
}
.keys button.operator:hover {
background-color: #e08080;
}
.keys button.clear {
background-color: #c0c0c0;
}
.keys button.clear:hover {
background-color: #b0b0b0;
}
.keys button.calculate {
background-color: #70c0a0;
color: white;
}
.keys button.calculate:hover {
background-color: #50b080;
}
```
JavaScript:
```javascript
const display = document.querySelector('.display');
const keys = document.querySelector('.keys');
const operators = ['+', '-', '*', '/'];
keys.addEventListener('click', event => {
if (event.target.matches('button')) {
const key = event.target;
const action = key.value;
const keyContent = key.textContent;
const displayValue = display.value;
if (!action) {
if (displayValue === '0') {
display.value = keyContent;
} else {
display.value += keyContent;
}
} else if (operators.includes(action)) {
const lastChar = displayValue[displayValue.length - 1];
if (lastChar && !operators.includes(lastChar)) {
display.value += action;
}
} else if (action === '.') {
const lastNumber = displayValue.split(/[-+*/]/).pop();
if (!lastNumber.includes('.')) {
display.value += action;
}
} else if (action === 'clear') {
display.value = '0';
} else if (action === '=') {
const expression = displayValue;
const result = eval(expression);
display.value = result;
}
}
});
```
这是一个基本的计算器,可以进行加、减、乘、除、小数点和清除操作。注意,这是一个演示示例,使用 `eval()` 函数进行计算,实际上在生产环境中,应该避免直接使用 `eval()` 函数,因为它可能存在安全问题。
阅读全文