表單驗證、帳號輸入、驗證碼等場景常需**強制英文/數字輸入**,禁止中文輸入法(IME)。
<input type="text" style="ime-mode: disabled">
<input type="text"
onpaste="return false"
ondragenter="return false"
oncontextmenu="return false"
style="ime-mode: disabled">
| 屬性 | 作用 |
|---|---|
onpaste="return false" | 阻止貼上 (Ctrl+V / 右鍵貼上) |
ondragenter="return false" | 阻止拖拽文字進入 |
oncontextmenu="return false" | 阻止右鍵選單(防繞過貼上限制) |
ime-mode: disabled | 嘗試禁用 IME(相容舊瀏覽器) |
不依賴內聯屬性,改用 `addEventListener` 統一管理,並即時過濾非法字元:
<input type="text" id="englishOnly" placeholder="僅限英文數字">
<script>
const input = document.getElementById('englishOnly');
// 1. 阻止貼上、拖拽、右鍵
['paste', 'dragenter', 'drop', 'contextmenu'].forEach(evt => {
input.addEventListener(evt, e => e.preventDefault());
});
// 2. 即時過濾:只保留 ASCII 列印字元(字母、數字、常用符號)
input.addEventListener('input', function() {
// 移除所有非 ASCII 列印字元 (範圍 33-126,含空格可自行調整)
this.value = this.value.replace(/[^\x20-\x7E]/g, '');
});
// 3. 可選:阻止輸入法組合事件中輸入中文(較激進)
input.addEventListener('compositionstart', e => e.target.dataset.composing = true);
input.addEventListener('compositionend', e => {
e.target.dataset.composing = false;
// 組合結束後再過濾一次
e.target.value = e.target.value.replace(/[^\x20-\x7E]/g, '');
});
</script>
| 方案 | 相容性 | 防貼上 | 防拖拽 | 維護性 |
|---|---|---|---|---|
| ime-mode 單獨使用 | 差 (已棄用) | ❌ | ❌ | 高 |
| 內聯事件組合 | 佳 | ✅ | ✅ | 低 (混雜 HTML/JS) |
| JS 事件監聽 + 正則過濾 | 最佳 (全瀏覽器) | ✅ | ✅ | 高 (關注點分離) |
<input type="text" id="numbersOnly" inputmode="numeric" pattern="[0-9]*">
<script>
document.getElementById('numbersOnly').addEventListener('input', function() {
this.value = this.value.replace(/\D/g, ''); // 只保留數字
});
</script>
**建議**:採用「JS 事件監聽 + 正則過濾」方案,既相容現代瀏覽器,又能徹底阻擋中文輸入與繞過行為,且程式碼結構清晰易維護。