用JS代码写一个计算器
时间: 2023-11-18 16:05:32 浏览: 49
抱歉,我是语言模型AI,无法提供页面。以下是一个简单计算器的JS代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>计算器</title>
<style>
#result {
width: 200px;
height: 30px;
font-size: 20px;
text-align: right;
padding-right: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
.button {
width: 50px;
height: 50px;
font-size: 20px;
margin: 5px;
border-radius: 5px;
background-color: #eee;
cursor: pointer;
}
.button:hover {
background-color: #ddd;
}
#clear {
background-color: #f00;
color: #fff;
}
</style>
</head>
<body>
<div id="result">0</div>
<div>
<div class="button" onclick="addNumber('7')">7</div>
<div class="button" onclick="addNumber('8')">8</div>
<div class="button" onclick="addNumber('9')">9</div>
<div class="button" onclick="addOperation('+')">+</div>
</div>
<div>
<div class="button" onclick="addNumber('4')">4</div>
<div class="button" onclick="addNumber('5')">5</div>
<div class="button" onclick="addNumber('6')">6</div>
<div class="button" onclick="addOperation('-')">-</div>
</div>
<div>
<div class="button" onclick="addNumber('1')">1</div>
<div class="button" onclick="addNumber('2')">2</div>
<div class="button" onclick="addNumber('3')">3</div>
<div class="button" onclick="addOperation('*')">*</div>
</div>
<div>
<div class="button" onclick="addNumber('0')">0</div>
<div class="button" onclick="addNumber('.')">.</div>
<div class="button" onclick="calculate()">=</div>
<div class="button" onclick="addOperation('/')">/</div>
</div>
<div>
<div class="button" onclick="clearResult()" id="clear">C</div>
</div>
<script>
var result = document.getElementById("result");
var number1 = null;
var number2 = null;
var operation = null;
var isDecimal = false;
function addNumber(num) {
if (num === '.') {
if (isDecimal) {
return;
} else {
isDecimal = true;
}
}
if (operation === null) {
if (number1 === null) {
number1 = num;
} else {
number1 += num;
}
result.innerHTML = number1;
} else {
if (number2 === null) {
number2 = num;
} else {
number2 += num;
}
result.innerHTML = number2;
}
}
function addOperation(op) {
if (number1 === null) {
return;
}
if (number2 !== null) {
calculate();
}
operation = op;
isDecimal = false;
}
function calculate() {
if (number1 === null || operation === null || number2 === null) {
return;
}
var num1 = parseFloat(number1);
var num2 = parseFloat(number2);
var res;
switch (operation) {
case '+':
res = num1 + num2;
break;
case '-':
res = num1 - num2;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num1 / num2;
break;
}
result.innerHTML = res.toString();
number1 = res.toString();
number2 = null;
operation = null;
isDecimal = false;
}
function clearResult() {
result.innerHTML = '0';
number1 = null;
number2 = null;
operation = null;
isDecimal = false;
}
</script>
</body>
</html>
```
阅读全文