HTML和js制作计算器
时间: 2024-04-29 17:26:43 浏览: 67
可以使用HTML和JavaScript来制作一个简单的计算器。以下是一个示例代码:
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<title>计算器</title>
<script src="calculator.js"></script>
</head>
<body>
<h1>计算器</h1>
<input type="text" id="result" disabled>
<br><br>
<button onclick="addNumber('1')">1</button>
<button onclick="addNumber('2')">2</button>
<button onclick="addNumber('3')">3</button>
<button onclick="addOperator('+')">+</button>
<br>
<button onclick="addNumber('4')">4</button>
<button onclick="addNumber('5')">5</button>
<button onclick="addNumber('6')">6</button>
<button onclick="addOperator('-')">-</button>
<br>
<button onclick="addNumber('7')">7</button>
<button onclick="addNumber('8')">8</button>
<button onclick="addNumber('9')">9</button>
<button onclick="addOperator('*')">*</button>
<br>
<button onclick="addNumber('0')">0</button>
<button onclick="addOperator('/')">/</button>
<button onclick="clearResult()">C</button>
<button onclick="calculate()">=</button>
</body>
</html>
```
JavaScript代码(保存为calculator.js文件):
```
var currentNumber = '0';
var currentOperator = '+';
var result = 0;
function addNumber(number) {
if (currentNumber == '0') {
currentNumber = number;
} else {
currentNumber += number;
}
document.getElementById('result').value = currentNumber;
}
function addOperator(operator) {
calculate();
currentOperator = operator;
currentNumber = '0';
}
function clearResult() {
currentNumber = '0';
currentOperator = '+';
result = 0;
document.getElementById('result').value = currentNumber;
}
function calculate() {
var number = parseInt(currentNumber);
switch (currentOperator) {
case '+':
result += number;
break;
case '-':
result -= number;
break;
case '*':
result *= number;
break;
case '/':
result /= number;
break;
default:
result = 0;
break;
}
currentOperator = '+';
currentNumber = '0';
document.getElementById('result').value = result;
}
```
这个计算器只支持加、减、乘、除四则运算,可以根据需求进行修改和扩展。
阅读全文