問題
登錄頁面,輸入驗(yàn)證碼的時(shí)候,自己在代碼里加了對(duì)Enter鍵的監(jiān)聽,導(dǎo)致與輸入法沖突。具體現(xiàn)象是:驗(yàn)證碼是英文的,用中文輸入法輸入,在有候選字的情況下按Enter,這時(shí)先觸發(fā)登錄,沒有先轉(zhuǎn)化為code。
如圖

FinalVideo_1622033824.952332.gif
資料
經(jīng)過查找compositionstart和compositionend這兩個(gè)方法剛好滿足需求。
簡單的說一下這兩個(gè)方法的屬性。
compositionstart
MDN文檔地址: https://developer.mozilla.org/zh-CN/docs/Web/Events/compositionstart
解釋:
文本合成系統(tǒng)如input method editor(即輸入法編輯器)開始新的輸入合成時(shí)會(huì)觸發(fā)compositionstart事件。
MDN文檔地址: https://developer.mozilla.org/zh-CN/docs/Web/Events/compositionend
解釋:
當(dāng)文本段落的組成完成或取消時(shí), compositionend 事件將被觸發(fā) (具有特殊字符的觸發(fā), 需要一系列鍵和其他輸入, 如語音識(shí)別或移動(dòng)中的字詞建議)。
看了下vue的源碼,也是通過這種方式來解決輸入法按鍵沖突的問題。
https://github.com/vuejs/vue/blob/dev/dist/vue.js#L8482
實(shí)現(xiàn)
- jQuery實(shí)現(xiàn)
const $input = $('#ipt');
let composing = false;
$input
.on('compositionstart', () => {
composing = true;
})
.on('compositionend', () => {
composing = false;
})
.on('keyup', () => {
if (!composing) {
// do something ...
}
})
-
vue的demo
<!DOCTYPE html> <html> <head> <title>Enter鍵與輸入法候選詞</title> <script src="https://unpkg.com/vue"></script> </head> <body> <div id="app"> <h2>Enter鍵與輸入法候選詞</h2> <section> <input type="checkbox" v-model="judgeComposing">開啟composing判斷 </section> <section> <div> <form> <div> <label for="username ">用戶名</label> <input ref="username " type="text " id="username " laceholder="輸入用戶名 "> </div> <div> <label for="code ">用中文輸入法輸入zhongwen</label> <input ref="code " type="text " id="code " laceholder="輸入zhongwen "> </div> <button @click="loginAction ">登錄</button> </form> </div> </section> <section> <div style="margin-top: 20px; ">{{log}}</div> </section> </div> <script> var app = new Vue({ el: '#app', data: { message: 'Hello Vue!', log: '', judgeComposing: true }, watch: { judgeComposing: (value) => { app.log += ("是否開啟composing:" + value) } }, mounted() { this.log += "Mounted finished. \n " document.onkeydown = (e) => { e = window.event || e if (e.code === 'Enter' || e.code === 'NumpadEnter') { // 驗(yàn)證在登錄界面和按得鍵是回車鍵enter this.log += "按下了Enter。 \n " if (this.judgeComposing) { const someOneIsComposing = [this.$refs.username, this.$refs.code].reduce((composing, component) => { return composing || component.isComposing }, false) if (someOneIsComposing === false) { this.loginAction() } } else { this.loginAction() } } } }, methods: { loginAction() { alert("loginAction ") } }, }) </script> </body> <style> </style> </html>