偵測 KeyboardEvent 時,判斷使用者是否正在操作輸入法視窗(選字)
前情提要
遇到一個需求,當使用者在輸入框輸入文字時,要彈出自動完成的選項,按上下鍵時可以從移動選項
結果遇到使用者正在操作輸入法的選字,結果上下鍵也一併影響了自動完成內的選項位置
當使用者按下Enter後,也很漂亮的幫使用者選擇了其中一個選項
測試了一下,找到了可以判斷的參數
1.先準備一下範例程式碼
2.Html
- prevent是為了防止使用者選字時游標會依據原本行為亂跑,按上下會跑回最前面或最後面
<input @keyup.up.prevent="movePointerUp"
@keydown.up.prevent=""
@keyup.down.prevent="movePointerDown"
@keydown.down.prevent=""
/>
2.js
movePointerDown(event) {
// anything
},
movePointerUp(event) {
// anything
},
3.接著比對了一下單純選擇選項時的event內容以及觸發選字視窗時的event內容,發現了一個參數差異 "isComposing"
4.查詢了一下MDN Web Docs,看來是他沒錯了
- The
KeyboardEvent.isComposing
read-only property returns aBoolean
value indicating if the event is fired aftercompositionstart
and beforecompositionend
. -
The
compositionstart
event is fired when a text composition system such as an input method editor starts a new composition session.For example, this event could be fired after a user starts entering a Chinese character using a Pinyin IME.
5.接著回頭調整一下 js,加上一個 if 判斷 event.isComposing
movePointerDown(event) {
if (event.isComposing)
{
return;
}
// anything
},
movePointerUp(event) {
if (event.isComposing)
{
return;
}
// anything
},
6.測試一下,看起來是正確了
KeyboardEvent.isComposing https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/isComposing
Element: compositionstart event https://developer.mozilla.org/en-US/docs/Web/API/Element/compositionstart_event