js简易计算器
时间: 2023-07-23 15:18:58 浏览: 46
好的,以下是一个简易的 JavaScript 计算器的代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>简易计算器</title>
<style>
#calculator {
display: inline-block;
border: 1px solid black;
padding: 10px;
}
input[type="button"] {
width: 50px;
height: 50px;
font-size: 20px;
}
</style>
</head>
<body>
<div id="calculator">
<input type="text" id="result" disabled>
<br>
<input type="button" value="7" onclick="press('7')">
<input type="button" value="8" onclick="press('8')">
<input type="button" value="9" onclick="press('9')">
<input type="button" value="+" onclick="press('+')">
<br>
<input type="button" value="4" onclick="press('4')">
<input type="button" value="5" onclick="press('5')">
<input type="button" value="6" onclick="press('6')">
<input type="button" value="-" onclick="press('-')">
<br>
<input type="button" value="1" onclick="press('1')">
<input type="button" value="2" onclick="press('2')">
<input type="button" value="3" onclick="press('3')">
<input type="button" value="*" onclick="press('*')">
<br>
<input type="button" value="0" onclick="press('0')">
<input type="button" value="C" onclick="clearResult()">
<input type="button" value="=" onclick="calculate()">
<input type="button" value="/" onclick="press('/')">
</div>
<script>
function press(value) {
document.getElementById("result").value += value;
}
function clearResult() {
document.getElementById("result").value = "";
}
function calculate() {
var result = eval(document.getElementById("result").value);
document.getElementById("result").value = result;
}
</script>
</body>
</html>
```
这个代码实现了一个简单的四则运算计算器,包含加、减、乘、除和清除等功能。你可以将代码复制到一个 HTML 文件中运行,然后在浏览器中打开该文件即可使用。