1+2=3)。<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>簡易計算機</title>
<style>
body { font-family: sans-serif; display: flex; justify-content: center; margin-top: 3rem; }
table { border-collapse: collapse; }
td { padding: 0; }
input[type=text] { width: 100%; height: 40px; font-size: 1.5rem; text-align: right; padding: 0 0.5rem; box-sizing: border-box; border: 1px solid #ccc; }
input[type=button] { width: 60px; height: 50px; font-size: 1.2rem; cursor: pointer; border: 1px solid #bbb; background: #f9f9f9; }
input[type=button]:active { background: #e0e0e0; }
.operator { background: #ffe0b2; }
.equal { background: #c8e6c9; }
</style>
</head>
<body>
<table>
<tr>
<td colspan="4"><input type="text" id="display" readonly></td>
</tr>
<tr>
<td><input type="button" value="1" onclick="appendNum('1')"></td>
<td><input type="button" value="2" onclick="appendNum('2')"></td>
<td><input type="button" value="3" onclick="appendNum('3')"></td>
<td><input type="button" class="operator" value="+" onclick="appendNum('+')"></td>
</tr>
<tr>
<td><input type="button" value="4" onclick="appendNum('4')"></td>
<td><input type="button" value="5" onclick="appendNum('5')"></td>
<td><input type="button" value="6" onclick="appendNum('6')"></td>
<td><input type="button" class="operator" value="-" onclick="appendNum('-')"></td>
</tr>
<tr>
<td><input type="button" value="7" onclick="appendNum('7')"></td>
<td><input type="button" value="8" onclick="appendNum('8')"></td>
<td><input type="button" value="9" onclick="appendNum('9')"></td>
<td><input type="button" class="operator" value="×" onclick="appendNum('*')"></td>
</tr>
<tr>
<td><input type="button" value="0" onclick="appendNum('0')"></td>
<td><input type="button" value="." onclick="appendNum('.')"></td>
<td><input type="button" class="equal" value="=" onclick="calculate()"></td>
<td><input type="button" class="operator" value="÷" onclick="appendNum('/')"></td>
</tr>
</table>
<script>
const display = document.getElementById('display');
let clearFlag = false; // 運算完成後,下一個輸入應清空螢幕
function appendNum(val) {
if (clearFlag) {
display.value = '';
clearFlag = false;
}
// 避免連續運算符
const lastChar = display.value.slice(-1);
if ('+-*/'.includes(val) && '+-*/'.includes(lastChar)) {
display.value = display.value.slice(0, -1) + val;
return;
}
display.value += val;
}
function calculate() {
try {
// 安全評估:僅允許數字、運算符、小數點
if (!/^[\d+\-*/.()]+$/.test(display.value)) throw new Error('非法字元');
const result = eval(display.value);
if (!isFinite(result)) throw new Error('除以零或溢位');
display.value += '=' + result;
} catch (e) {
display.value = '錯誤';
}
clearFlag = true;
}
</script>
</body>
</html>
<input type="text" id="display"> 同時作為輸入與結果顯示,設為 readonly 避免鍵盤干擾。clearFlag: 運算完成後設為 true,下一次點擊數字鍵時先清空螢幕,模擬實體計算機行為。eval() 計算: 為教學示範簡化邏輯;實務專案建議自行實作解析器或使用 math.js 等庫以避免安全風險。:active 回饋增強手感。這個計算機範例展示了如何用極簡的 HTML/CSS/JS 打造一個功能完整、互動流暢的網頁小工具,是前端入門的經典練習專案。