给我一个java script计算器代码显示在网页上
时间: 2024-05-01 21:19:44 浏览: 190
以下是一个基本的 JavaScript 计算器代码,可以在网页上进行显示:
HTML 代码:
```
<!DOCTYPE html>
<html>
<head>
<title>JavaScript 计算器</title>
<meta charset="UTF-8">
<style>
input[type="button"] {
width: 50px;
height: 50px;
font-size: 20px;
margin: 5px;
cursor: pointer;
}
input[type="text"] {
width: 205px;
height: 50px;
font-size: 20px;
margin: 5px;
text-align: right;
}
</style>
</head>
<body>
<table border="1">
<tr>
<td colspan="4"><input type="text" id="display" disabled></td>
</tr>
<tr>
<td><input type="button" value="7" onclick="calculate('7')"></td>
<td><input type="button" value="8" onclick="calculate('8')"></td>
<td><input type="button" value="9" onclick="calculate('9')"></td>
<td><input type="button" value="+" onclick="calculate('+')"></td>
</tr>
<tr>
<td><input type="button" value="4" onclick="calculate('4')"></td>
<td><input type="button" value="5" onclick="calculate('5')"></td>
<td><input type="button" value="6" onclick="calculate('6')"></td>
<td><input type="button" value="-" onclick="calculate('-')"></td>
</tr>
<tr>
<td><input type="button" value="1" onclick="calculate('1')"></td>
<td><input type="button" value="2" onclick="calculate('2')"></td>
<td><input type="button" value="3" onclick="calculate('3')"></td>
<td><input type="button" value="*" onclick="calculate('*')"></td>
</tr>
<tr>
<td><input type="button" value="0" onclick="calculate('0')"></td>
<td><input type="button" value="." onclick="calculate('.')"></td>
<td><input type="button" value="C" onclick="clearDisplay()"></td>
<td><input type="button" value="/" onclick="calculate('/')"></td>
</tr>
<tr>
<td colspan="4"><input type="button" value="=" onclick="calculate('=')"></td>
</tr>
</table>
<script src="calculator.js"></script>
</body>
</html>
```
JavaScript 代码:
```
var operand1 = "";
var operand2 = "";
var operator = "";
var result = "";
function calculate(value) {
if (value === "C") {
clearDisplay();
} else if (value === "+" || value === "-" || value === "*" || value === "/") {
operator = value;
operand1 = result;
operand2 = "";
result = "";
} else if (value === "=") {
if (operand1 !== "" && operand2 !== "" && operator !== "") {
result = eval(operand1 + operator + operand2);
document.getElementById("display").value = result;
operand1 = "";
operand2 = "";
operator = "";
}
} else {
if (operator === "") {
operand1 += value;
document.getElementById("display").value = operand1;
} else {
operand2 += value;
document.getElementById("display").value = operand2;
}
}
}
function clearDisplay() {
operand1 = "";
operand2 = "";
operator = "";
result = "";
document.getElementById("display").value = "";
}
```
你可以将以上代码保存为两个文件,一个是 HTML 文件,一个是 JavaScript 文件,然后在浏览器中打开 HTML 文件,就可以看到一个基本的 JavaScript 计算器了。
阅读全文
相关推荐















