實現一個簡易計算機輸入介面,支援:
<input class="tf" type="text" id="tf" readonly /> <!-- 唯讀防止輸入法干擾 -->
<div class="keypad">
<button data-key="7">7</button>
<button data-key="8">8</button>
<button data-key="9">9</button>
<button data-key="4">4</button>
<button data-key="5">5</button>
<button data-key="6">6</button>
<button data-key="1">1</button>
<button data-key="2">2</button>
<button data-key="3">3</button>
<button data-key="0" class="wide">0</button>
<button data-key=".">.</button>
<button data-key="backspace" class="wide">⌫</button>
<button data-key="clear">C</button>
<button data-key="enter" class="wide">=</button>
</div>
.tf {
width: 100%; height: 60px;
font-size: 28px; font-family: 'SF Mono', 'Monospace';
text-align: right; padding: 0 16px;
background: #000; color: #fff; border: 2px solid #333;
border-radius: 8px; box-sizing: border-box;
}
.keypad { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin-top: 12px; }
.keypad button {
height: 56px; font-size: 20px; font-weight: 500;
background: #333; color: #fff; border: none; border-radius: 8px;
cursor: pointer; transition: background 0.1s;
}
.keypad button:hover { background: #444; }
.keypad button:active { background: #555; }
.keypad button.wide { grid-column: span 2; }
.keypad button[data-key="backspace"] { background: #d32f2f; }
.keypad button[data-key="enter"] { background: #388e3c; }
class CalculatorInput {
constructor(inputId) {
this.input = document.getElementById(inputId);
this.value = "0";
this.bindEvents();
}
bindEvents() {
// 滑鼠點擊按鈕
document.querySelector(".keypad").addEventListener("click", (e) => {
const btn = e.target.closest("button");
if (!btn) return;
this.handleKey(btn.dataset.key);
});
// 鍵盤支援
document.addEventListener("keydown", (e) => {
const map = {
"0":"0","1":"1","2":"2","3":"3","4":"4",
"5":"5","6":"6","7":"7","8":"8","9":"9",
".":".", "Backspace":"backspace", "Delete":"clear",
"Enter":"enter", "Escape":"clear"
};
if (map[e.key]) {
e.preventDefault();
this.handleKey(map[e.key]);
}
});
}
handleKey(key) {
switch (key) {
case "0": case "1": case "2": case "3": case "4":
case "5": case "6": case "7": case "8": case "9":
this.appendDigit(key);
break;
case ".":
this.appendDecimal();
break;
case "backspace":
this.backspace();
break;
case "clear":
this.clear();
break;
case "enter":
this.calculate();
break;
}
this.updateDisplay();
}
appendDigit(digit) {
if (this.value === "0") {
this.value = digit; // 替換前導零
} else if (this.value.length < 16) { // 限制長度
this.value += digit;
}
}
appendDecimal() {
if (!this.value.includes(".")) {
this.value += ".";
}
}
backspace() {
// 核心邏輯:移除最後一字符
if (this.value.length > 1) {
this.value = this.value.slice(0, -1);
} else {
this.value = "0"; // 單字符時重置為 0
}
}
clear() { this.value = "0"; }
calculate() {
try {
// 簡易 eval(實務請用表達式解析器)
this.value = String(eval(this.value));
} catch (e) {
this.value = "Error";
setTimeout(() => this.clear(), 1500);
}
}
updateDisplay() {
this.input.value = this.value;
}
}
// 初始化
new CalculatorInput("tf");
| 方法 | 代碼 | 特點 |
|---|---|---|
| slice (推薦) | str.slice(0, -1) | 語意清晰、不修改原字串、效能佳 |
| substring | str.substring(0, str.length - 1) | 相容舊瀏覽器、參數順序不敏感 |
| substr (已棄用) | str.substr(0, str.length - 1) | 非標準、不推薦新代碼使用 |
| 正則替換 | str.replace(/.$/, '') | 功能強大但大材小用、效能較差 |
| 陣列操作 | [...str].pop() && [...str].join('') | 支援 Unicode 組合字符、效能最差 |
appendDigit(digit) {
// 科學記號、工程記號等進階格式可擴充
if (this.value === "0" || this.value === "-0") {
this.value = digit;
} else if (this.value === "Error") {
this.value = digit;
} else if (this.value.length < 16) {
this.value += digit;
}
}
backspace() {
// 處理負號保護:"-5" 退格後變 "0" 而非 "-"
if (this.value.length === 2 && this.value.startsWith("-")) {
this.value = "0";
} else if (this.value.length > 1) {
this.value = this.value.slice(0, -1);
} else {
this.value = "0";
}
}
aria-label 於每個按鈕:<button data-key="7" aria-label="數字 7">role="application" 於鍵盤容器,宣告自定義鍵盤互動aria-live="polite" 於輸入框@media (prefers-contrast: high)計算機輸入介面看似簡單,實則涵蓋字串操作、狀態管理、事件處理、輸入驗證、無障礙等核心前端技能。採用 Class 封裝、關注點分離(輸入邏輯與顯示分離)、支援鍵盤/滑鼠雙模式,是打造專業級 UI 元件的基礎範式。