使用html制作一个计算器
时间: 2023-08-14 13:04:57 浏览: 39
好的,这里给您提供一个简单的计算器HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>计算器</title>
<meta charset="utf-8">
<style type="text/css">
.container {
width: 300px;
margin: 0 auto;
padding: 10px;
background-color: #f7f7f7;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0,0,0,0.2);
}
h1 {
text-align: center;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin-bottom: 10px;
font-size: 24px;
border: none;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0,0,0,0.2);
text-align: right;
}
input[type="button"] {
width: 48%;
padding: 10px;
margin: 5px;
font-size: 24px;
border: none;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0,0,0,0.2);
background-color: #4CAF50;
color: #fff;
cursor: pointer;
}
input[type="button"]:hover {
background-color: #3e8e41;
}
.clear {
clear: both;
}
</style>
</head>
<body>
<div class="container">
<h1>计算器</h1>
<input type="text" id="result" readonly>
<input type="button" value="1" onclick="insert('1')">
<input type="button" value="2" onclick="insert('2')">
<input type="button" value="3" onclick="insert('3')">
<input type="button" value="+" onclick="insert('+')">
<input type="button" value="-" onclick="insert('-')">
<input type="button" value="4" onclick="insert('4')">
<input type="button" value="5" onclick="insert('5')">
<input type="button" value="6" onclick="insert('6')">
<input type="button" value="*" onclick="insert('*')">
<input type="button" value="/" onclick="insert('/')">
<input type="button" value="7" onclick="insert('7')">
<input type="button" value="8" onclick="insert('8')">
<input type="button" value="9" onclick="insert('9')">
<input type="button" value="." onclick="insert('.')">
<input type="button" value="C" onclick="clearResult()">
<input type="button" value="0" onclick="insert('0')">
<input type="button" value="=" onclick="calculate()">
<div class="clear"></div>
</div>
<script type="text/javascript">
function insert(num) {
document.getElementById('result').value += num;
}
function clearResult() {
document.getElementById('result').value = '';
}
function calculate() {
var result = eval(document.getElementById('result').value);
document.getElementById('result').value = result;
}
</script>
</body>
</html>
```
这个计算器支持加、减、乘、除四则运算以及小数点和清空操作。您可以将这段代码保存为一个HTML文件,并在浏览器中打开以使用。