新建1.html,编写简单计算器,效果如下图所示:
时间: 2024-05-16 19:13:06 浏览: 64
实现一个html计算器效果
抱歉,我是一名语言模型,无法提供图形界面。但我可以提供计算器的代码实现,你可以在本地运行代码查看效果。
```html
<!DOCTYPE html>
<html>
<head>
<title>简单计算器</title>
<style type="text/css">
#calculator {
width: 300px;
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
margin: 20px auto;
}
input[type="text"] {
width: 100%;
height: 40px;
padding: 5px;
font-size: 20px;
box-sizing: border-box;
margin-bottom: 10px;
}
input[type="button"] {
width: 25%;
height: 40px;
font-size: 20px;
box-sizing: border-box;
background-color: #f2f2f2;
border: 1px solid #ccc;
border-radius: 3px;
margin-right: 5px;
margin-bottom: 5px;
cursor: pointer;
}
input[type="button"]:hover {
background-color: #ccc;
}
input[type="button"]:active {
background-color: #999;
}
</style>
</head>
<body>
<div id="calculator">
<input type="text" id="result" disabled>
<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('+')">
<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('-')">
<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('*')">
<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('/')">
</div>
<script type="text/javascript">
var result = document.getElementById('result');
var num1 = '';
var num2 = '';
var operator = '';
// 添加数字
function addNumber(num) {
if (operator === '') {
num1 += num;
result.value = num1;
} else {
num2 += num;
result.value = num2;
}
}
// 添加运算符
function addOperator(op) {
operator = op;
}
// 清空结果
function clearResult() {
num1 = '';
num2 = '';
operator = '';
result.value = '';
}
// 计算结果
function calculate() {
var res;
switch (operator) {
case '+':
res = parseInt(num1) + parseInt(num2);
break;
case '-':
res = parseInt(num1) - parseInt(num2);
break;
case '*':
res = parseInt(num1) * parseInt(num2);
break;
case '/':
res = parseInt(num1) / parseInt(num2);
break;
}
result.value = res;
num1 = '';
num2 = '';
operator = '';
}
</script>
</body>
</html>
```
这个计算器由一个输入框和多个按钮组成,每个按钮代表一个数字或运算符。按钮的点击事件会调用对应的 JavaScript 函数,从而实现计算器的功能。
阅读全文