帮我写一个网页版计算器代码
时间: 2024-06-06 20:08:42 浏览: 101
<!DOCTYPE html>
<html>
<head>
<title>简易计算器</title>
<meta charset="utf-8">
<style type="text/css">
body {
margin: 0;
padding: 0;
background-color: #f0f0f0;
}
h1 {
text-align: center;
font-size: 36px;
color: #333;
margin-top: 50px;
}
#calculator {
width: 400px;
margin: 50px auto;
background-color: #fff;
border-radius: 5px;
padding: 20px;
}
input[type="text"] {
width: 100%;
height: 50px;
font-size: 24px;
padding: 5px 10px;
border-radius: 5px;
border: 1px solid #ccc;
margin-bottom: 20px;
}
input[type="button"] {
width: 25%;
height: 50px;
font-size: 24px;
padding: 5px 10px;
border-radius: 5px;
border: none;
background-color: #4CAF50;
color: #fff;
cursor: pointer;
}
input[type="button"]:hover {
background-color: #333;
}
</style>
</head>
<body>
<h1>简易计算器</h1>
<div id="calculator">
<input type="text" id="result" placeholder="请输入表达式">
<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="0" onclick="addNumber('0')">
<input type="button" value="C" onclick="clearResult()">
<input type="button" value="=" onclick="calculate()">
<input type="button" value="/" onclick="addOperator('/')">
</div>
<script type="text/javascript">
function addNumber(num) {
document.getElementById("result").value += num;
}
function addOperator(operator) {
document.getElementById("result").value += operator;
}
function clearResult() {
document.getElementById("result").value = "";
}
function calculate() {
var result = eval(document.getElementById("result").value);
document.getElementById("result").value = result;
}
</script>
</body>
</html>
阅读全文