js实现windows计算器
时间: 2023-06-27 19:04:49 浏览: 208
js实现计算器
下面是一个简单的实现:
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Windows Calculator</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="calculator">
<div class="output">
<div id="result">0</div>
</div>
<div class="buttons">
<button onclick="clearResult()">C</button>
<button onclick="deleteLast()">←</button>
<button onclick="calculate('%')">%</button>
<button onclick="calculate('/')">÷</button>
<button onclick="addDigit(7)">7</button>
<button onclick="addDigit(8)">8</button>
<button onclick="addDigit(9)">9</button>
<button onclick="calculate('*')">x</button>
<button onclick="addDigit(4)">4</button>
<button onclick="addDigit(5)">5</button>
<button onclick="addDigit(6)">6</button>
<button onclick="calculate('-')">-</button>
<button onclick="addDigit(1)">1</button>
<button onclick="addDigit(2)">2</button>
<button onclick="addDigit(3)">3</button>
<button onclick="calculate('+')">+</button>
<button onclick="addDigit(0)">0</button>
<button onclick="addDigit('.')">.</button>
<button class="equal" onclick="calculate('=')">=</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
```
CSS代码:
```
.calculator {
width: 300px;
margin: 50px auto;
background-color: #eee;
border-radius: 5px;
box-shadow: 1px 1px 5px rgba(0,0,0,0.3);
}
.output {
height: 60px;
padding: 10px;
text-align: right;
font-size: 30px;
font-weight: bold;
background-color: #fff;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 5px;
padding: 10px;
background-color: #ccc;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
}
button {
width: 100%;
height: 50px;
font-size: 20px;
font-weight: bold;
border-radius: 5px;
border: none;
background-color: #fff;
cursor: pointer;
}
button:hover {
background-color: #ddd;
}
.equal {
background-color: #f90;
color: #fff;
font-size: 24px;
}
.equal:hover {
background-color: #ff0;
}
```
JavaScript代码:
```
let result = document.getElementById('result');
let expression = '';
function addDigit(digit) {
expression += digit;
result.textContent = expression;
}
function clearResult() {
expression = '';
result.textContent = '0';
}
function deleteLast() {
expression = expression.slice(0, -1);
result.textContent = expression || '0';
}
function calculate(operator) {
if (operator === '=') {
expression = eval(expression).toString();
} else {
expression += operator;
}
result.textContent = expression;
}
```
这个计算器支持加减乘除、百分数、小数点和删除操作,可以进行基本的数学运算。但是需要注意的是,这个计算器使用了`eval`函数来计算表达式,可能存在一些安全问题,因此不应该在生产环境中使用。
阅读全文