html制作计算器
时间: 2023-07-03 21:12:49 浏览: 101
以下是一个简单的基于 HTML、CSS 和 JavaScript 的计算器示例:
HTML 代码:
```
<!DOCTYPE html>
<html>
<head>
<title>计算器</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="calculator">
<div class="display">
<input type="text" class="input" id="result" readonly>
</div>
<div class="buttons">
<button onclick="clearResult()">C</button>
<button onclick="backspace()">←</button>
<button onclick="insertSymbol('/')">÷</button>
<button onclick="insertSymbol('*')">×</button>
<button onclick="insertSymbol('7')">7</button>
<button onclick="insertSymbol('8')">8</button>
<button onclick="insertSymbol('9')">9</button>
<button onclick="insertSymbol('-')">-</button>
<button onclick="insertSymbol('4')">4</button>
<button onclick="insertSymbol('5')">5</button>
<button onclick="insertSymbol('6')">6</button>
<button onclick="insertSymbol('+')">+</button>
<button onclick="insertSymbol('1')">1</button>
<button onclick="insertSymbol('2')">2</button>
<button onclick="insertSymbol('3')">3</button>
<button onclick="calculate()">=</button>
<button onclick="insertSymbol('0')">0</button>
<button onclick="insertSymbol('.')">.</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
```
CSS 代码:
```
.calculator {
width: 300px;
margin: 100px auto;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 2px 2px 5px #ccc;
padding: 10px;
}
.display {
background-color: #f7f7f7;
border-radius: 5px;
padding: 5px;
margin-bottom: 10px;
}
.input {
width: 100%;
font-size: 24px;
text-align: right;
border: none;
outline: none;
}
.buttons button {
width: 50px;
height: 50px;
border-radius: 5px;
border: none;
margin: 5px;
font-size: 24px;
background-color: #f7f7f7;
cursor: pointer;
}
.buttons button:hover {
background-color: #ccc;
}
```
JavaScript 代码:
```
let result = document.getElementById("result");
function insertSymbol(symbol) {
result.value += symbol;
}
function clearResult() {
result.value = "";
}
function backspace() {
result.value = result.value.slice(0, -1);
}
function calculate() {
result.value = eval(result.value);
}
```
这个计算器支持加、减、乘、除、小数点、回退、清除和计算等基本操作。
阅读全文