本文分享如何用JavaScript製作一個簡易計算機,支援滑鼠點擊數字與運算符進行計算,並具備歸零功能。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#show {
width: 232px; height: 80px;
color: white;
border-radius: 5px 5px 0 0;
background-color: rgba(127, 128, 127, 1);
text-align: right;
border: none;
font-size: 45px;
outline: none;
}
table {
border: 1px solid black;
border-collapse: collapse;
width: 234px;
text-align: center;
font-size: 30px;
}
td {
height: 55px; width: 57.5px;
background-color: wheat;
}
td:active { background-color: coral; }
.aperation { background-color: rgb(245, 146, 62); color: white; }
#ape { background-color: wheat; color: #000000; }
</style>
</head>
<body>
<div>
<input type="text" id="show" />
<table border="1">
<tr>
<td id="clear">AC</td>
<td>+/-</td>
<td class="aperation" id="ape">%</td>
<td class="aperation">/</td>
</tr>
<tr>
<td class="num">7</td><td class="num">8</td><td class="num">9</td>
<td class="aperation">*</td>
</tr>
<tr>
<td class="num">4</td><td class="num">5</td><td class="num">6</td>
<td class="aperation">-</td>
</tr>
<tr>
<td class="num">1</td><td class="num">2</td><td class="num">3</td>
<td class="aperation">+</td>
</tr>
<tr>
<td colspan="2" class="num">0</td>
<td>.</td>
<td class="aperation" id="result">=</td>
</tr>
</table>
</div>
</body>
<script type="text/javascript">
var nums = document.getElementsByClassName("num"); // 數字鍵
var options = document.getElementsByClassName("aperation"); // 操作符
var result = document.getElementById("result"); // 等號
var clear = document.getElementById("clear"); // 歸零
var show = document.getElementById("show"); // 展示框
var numValue = ""; // 儲存數字
var optionC = ""; // 儲存操作符
var numTemp = ""; // 儲存暫存值
// 點擊數字鍵
for (var i = 0; i < nums.length; i++) {
nums[i].onclick = function() {
if (numValue == "0") { numValue = ""; }
numValue += this.innerHTML;
show.value = numValue;
};
}
// 點擊操作鍵
for (var i = 0; i < options.length - 1; i++) {
options[i].onclick = function() {
numTemp = numValue; // 記錄目前數字
optionC = this.innerHTML; // 記錄操作符
numValue = ""; // 清空數字
};
}
// 等號
result.onclick = function() {
show.value = eval(numTemp + optionC + numValue);
};
// 清零
clear.onclick = function() {
show.value = "0";
numValue = "";
optionC = "";
numTemp = "";
};
</script>
</html>
這個範例透過三個變數分別保存「目前輸入的數字」、「操作符」與「暫存值」,點擊等號時把它們拼接後交給 eval 求值,就得到計算結果。想進階的話,可以自行改寫運算邏輯,避免直接使用 eval 以兼顧安全性。