JavaScript编写计算器
时间: 2023-11-30 14:03:53 浏览: 63
Javascript编写的计算器
5星 · 资源好评率100%
好的,以下是一个简单的 JavaScript 计算器:
```html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Calculator</title>
<style>
body {
background-color: #f2f2f2;
font-family: Arial, sans-serif;
}
#calculator {
background-color: #fff;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
margin: 50px auto;
padding: 20px;
text-align: center;
width: 300px;
}
#result {
font-size: 36px;
margin-bottom: 20px;
}
button {
background-color: #4CAF50;
border: none;
border-radius: 5px;
color: #fff;
cursor: pointer;
font-size: 16px;
margin: 5px;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
}
button:hover {
background-color: #3e8e41;
}
button:active {
background-color: #3e8e41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
</style>
</head>
<body>
<div id="calculator">
<div id="result"></div>
<button onclick="clearDisplay()">C</button>
<button onclick="appendInput('(')">(</button>
<button onclick="appendInput(')')">)</button>
<button onclick="appendInput('/')">÷</button>
<br>
<button onclick="appendInput('7')">7</button>
<button onclick="appendInput('8')">8</button>
<button onclick="appendInput('9')">9</button>
<button onclick="appendInput('*')">x</button>
<br>
<button onclick="appendInput('4')">4</button>
<button onclick="appendInput('5')">5</button>
<button onclick="appendInput('6')">6</button>
<button onclick="appendInput('-')">-</button>
<br>
<button onclick="appendInput('1')">1</button>
<button onclick="appendInput('2')">2</button>
<button onclick="appendInput('3')">3</button>
<button onclick="appendInput('+')">+</button>
<br>
<button onclick="appendInput('0')">0</button>
<button onclick="appendInput('.')">.</button>
<button onclick="calculate()">=</button>
</div>
<script>
let input = '';
const result = document.getElementById('result');
function appendInput(value) {
input += value;
result.innerHTML = input;
}
function clearDisplay() {
input = '';
result.innerHTML = '';
}
function calculate() {
try {
const answer = eval(input);
result.innerHTML = answer;
input = '';
} catch (error) {
alert('Invalid input!');
clearDisplay();
}
}
</script>
</body>
</html>
```
这个计算器具有基本的加、减、乘、除、括号和小数点功能。你可以在 HTML 中添加更多的按钮来扩展其功能,比如添加正弦、余弦和正切等数学函数。
阅读全文