html页面简易计算器
时间: 2023-11-23 07:06:16 浏览: 229
简单计算器
以下是一个简单的HTML页面计算器的代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>简易计算器</title>
<style>
input[type="button"] {
width: 50px;
height: 50px;
font-size: 20px;
margin: 5px;
}
input[type="text"] {
width: 212px;
height: 50px;
font-size: 20px;
margin: 5px;
}
</style>
</head>
<body>
<input type="text" id="result" readonly>
<br>
<input type="button" value="1" onclick="addNumber('1')">
<input type="button" value="2" onclick="addNumber('2')">
<input type="button" value="3" onclick="addNumber('3')">
<input type="button" value="+" onclick="addOperator('+')">
<br>
<input type="button" value="4" onclick="addNumber('4')">
<input type="button" value="5" onclick="addNumber('5')">
<input type="button" value="6" onclick="addNumber('6')">
<input type="button" value="-" onclick="addOperator('-')">
<br>
<input type="button" value="7" onclick="addNumber('7')">
<input type="button" value="8" onclick="addNumber('8')">
<input type="button" value="9" onclick="addNumber('9')">
<input type="button" value="*" onclick="addOperator('*')">
<br>
<input type="button" value="C" onclick="clearResult()">
<input type="button" value="0" onclick="addNumber('0')">
<input type="button" value="=" onclick="calculate()">
<input type="button" value="/" onclick="addOperator('/')">
<script>
var result = document.getElementById("result");
var operator = "";
var num1 = "";
var num2 = "";
var flag = false;
function addNumber(num) {
if (flag) {
result.value = "";
flag = false;
}
result.value += num;
}
function addOperator(op) {
if (num1 == "") {
num1 = result.value;
} else {
num2 = result.value;
calculate();
num1 = result.value;
}
operator = op;
flag = true;
}
function clearResult() {
result.value = "";
num1 = "";
num2 = "";
operator = "";
}
function calculate() {
if (num1 != "" && num2 != "" && operator != "") {
var res = eval(num1 + operator + num2);
result.value = res;
num1 = res;
num2 = "";
operator = "";
flag = true;
}
}
</script>
</body>
</html>
```
阅读全文