計算器數字輸入框最多允許 5 位數字,超過則忽略後續輸入。
在數字按鈕的點擊處理函數中,檢查當前顯示值的長度,若小於限制則追加,否則不處理。
<input type="text" id="display" value="0" readonly>
<button onclick="addNum('1')">1</button>
<button onclick="addNum('2')">2</button>
<!-- 其他數字按鈕 -->
<script>
function addNum(n) {
const display = document.getElementById('display');
// 若當前為初始 "0",直接替換
if (display.value === '0') {
display.value = n;
}
// 長度檢查
else if (display.value.length < 5) {
display.value += n;
}
// 超過 5 位:靜默忽略或可提示用戶
}
</script>
!display.value.includes('.') 後再追加,且不計入長度限制或單獨限制小數位數。display.value = display.value.slice(0, -1) || '0';display.value = '0';input 事件監聽直接輸入(如鍵盤粘貼),統一攔截非法字符。<input type="number" max="99999"> 讓瀏覽器原生校驗(但樣式定制受限)。