html+js+css计算器,只需实现加减和等于功能
时间: 2024-03-14 17:44:00 浏览: 73
Calculator
好的,我可以为您提供一个简单的HTML+CSS+JavaScript计算器示例,可以实现加减和等于功能。以下是代码示例:
HTML代码:
```
<div class="calculator">
<input type="text" class="screen" readonly>
<div class="keys">
<button class="operator" value="+">+</button>
<button class="operator" value="-">-</button>
<button class="number" value="1">1</button>
<button class="number" value="2">2</button>
<button class="number" value="3">3</button>
<button class="number" value="4">4</button>
<button class="number" value="5">5</button>
<button class="number" value="6">6</button>
<button class="number" value="7">7</button>
<button class="number" value="8">8</button>
<button class="number" value="9">9</button>
<button class="number" value="0">0</button>
<button class="equals" value="=">=</button>
</div>
</div>
```
CSS代码:
```
.calculator {
width: 200px;
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
}
.screen {
width: 100%;
margin-bottom: 10px;
}
.keys {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 5px;
}
button {
font-size: 20px;
padding: 5px;
}
.operator {
background-color: #f2f2f2;
}
.number {
background-color: #fff;
}
```
JavaScript代码:
```
const screen = document.querySelector('.screen');
const keys = document.querySelector('.keys');
let firstNum = '';
let operator = '';
let secondNum = '';
keys.addEventListener('click', (e) => {
if (e.target.matches('.number')) {
if (operator === '') {
firstNum += e.target.value;
screen.value = firstNum;
} else {
secondNum += e.target.value;
screen.value = secondNum;
}
}
if (e.target.matches('.operator')) {
operator = e.target.value;
}
if (e.target.matches('.equals')) {
if (operator === '+') {
screen.value = parseInt(firstNum) + parseInt(secondNum);
} else if (operator === '-') {
screen.value = parseInt(firstNum) - parseInt(secondNum);
}
}
});
```
这个计算器的界面非常简单,只有一个文本框和一些按钮,您可以在文本框中输入数字,然后按下加号或减号按钮来选择您要执行的操作,最后按下等于号按钮来显示结果。请注意,这个示例只实现了加减和等于功能,如果需要实现更多的功能,需要扩展代码。
阅读全文