0%

Composition 事件

前陣子同事的專案需要在前端限制 textarea 只能輸入數字,主要的做法是使用 keydown 事件偵測現在按下的是什麼字,只要不是被允許的字元就不能夠輸入。

但是,中文輸入並不像英文輸入一樣按下按鍵就能直接完成輸入,而是會在注音或拼音組出一個字並按下 Enter 後,或者從 textarea focusout 才能完成輸入,在此之前 keydown 事件都將輸入視為 處理(Process) 的狀態而無法有效抵擋中文輸入,然而我們可以使用 JavaScript 監聽 compositionstartcompositionend 事件來達成。

範例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const textarea = document.querySelector('textarea');
const digits = Array.from(Array(10)).map((e, i) => i.toString());
const ctrlKeys = ["Enter", "Backspace", "Delete", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"];
let content = "";

document.addEventListener("compositionstart", (e) => {
content = textarea.value;
});

document.addEventListener("compositionend", (e) => {
textarea.value = content;
});

document.addEventListener("focusout", (e) => {
textarea.value = content;
});

textarea.addEventListener("paste", (e) => {
e.preventDefault();
});

textarea.addEventListener("keydown", (e) => {
if (!digits.includes(e.key.toString()) && !ctrlKeys.includes(e.key.toString())) {
e.preventDefault();
}
});
參考資料