用html和js编写成具有排布的1,2,3,4,5,6,7,8,9,+,-,*,/的计算器界面,并且可以实现计算
时间: 2024-06-05 08:06:30 浏览: 87
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Calculator</title>
<style>
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
background-color: #f2f2f2;
}
#calculator {
width: 300px;
margin: 50px auto;
background-color: #fff;
border-radius: 5px;
box-shadow: 0px 0px 10px rgba(0,0,0,0.2);
padding: 20px;
}
h2 {
margin: 0 0 20px 0;
text-align: center;
}
table {
margin: 0 auto;
border-collapse: separate;
border-spacing: 10px;
}
td {
padding: 10px;
background-color: #eee;
border-radius: 5px;
text-align: center;
cursor: pointer;
}
td:hover {
background-color: #ccc;
}
#result {
margin: 20px 0;
padding: 10px;
background-color: #ddd;
border-radius: 5px;
text-align: right;
font-size: 24px;
height: 50px;
line-height: 50px;
overflow: hidden;
word-wrap: break-word;
box-shadow: inset 0px 0px 10px rgba(0,0,0,0.2);
}
</style>
</head>
<body>
<div id="calculator">
<h2>Calculator</h2>
<table>
<tr>
<td onclick="displayText(1)">1</td>
<td onclick="displayText(2)">2</td>
<td onclick="displayText(3)">3</td>
<td onclick="displayText('-')">-</td>
</tr>
<tr>
<td onclick="displayText(4)">4</td>
<td onclick="displayText(5)">5</td>
<td onclick="displayText(6)">6</td>
<td onclick="displayText('+')">+</td>
</tr>
<tr>
<td onclick="displayText(7)">7</td>
<td onclick="displayText(8)">8</td>
<td onclick="displayText(9)">9</td>
<td onclick="displayText('*')">*</td>
</tr>
<tr>
<td></td>
<td onclick="displayText(0)">0</td>
<td onclick="displayText('.')">.</td>
<td onclick="displayText('/')">/</td>
</tr>
<tr>
<td colspan="4" onclick="clearResult()">Clear</td>
</tr>
</table>
<div id="result"></div>
</div>
<script>
var result = document.getElementById("result");
function displayText(text) {
if (text === '-') {
result.innerHTML += ' - ';
} else {
result.innerHTML += text;
}
}
function clearResult() {
result.innerHTML = '';
}
function calculate() {
var expression = result.innerHTML;
if (expression === '') {
result.innerHTML = '';
} else {
try {
result.innerHTML = eval(expression);
} catch (error) {
result.innerHTML = 'Error';
}
}
}
document.addEventListener("keydown", function(event) {
if (event.key === 'Enter') {
calculate();
} else if (event.key === 'Backspace') {
result.innerHTML = result.innerHTML.slice(0, -1);
} else if (!isNaN(event.key)) {
displayText(event.key);
} else if (event.key === '.') {
displayText('.');
} else if (event.key === '+') {
displayText('+');
} else if (event.key === '-') {
displayText('-');
} else if (event.key === '*') {
displayText('*');
} else if (event.key === '/') {
displayText('/');
}
});
</script>
</body>
</html>
阅读全文