使用输入法输入时如何避免input/textinput事件被意外触发?
解决方案
针对输入法复合输入场景下事件意外触发的问题,可通过composition系列事件标记输入状态,仅在字符确认输入后执行业务逻辑,实现代码如下:
jQuery 版本
let isComposing = false $('#name') .on('compositionstart', function() { isComposing = true }) .on('compositionend', function() { isComposing = false // 此处执行输入完成后的业务逻辑 const inputValue = $(this).val() }) .on('input change paste', function() { // 非输入法输入状态下直接执行业务逻辑 if (!isComposing) { const inputValue = $(this).val() } })
原生 JavaScript 版本
let isComposing = false const inputElement = document.getElementById('name') inputElement.addEventListener('compositionstart', () => { isComposing = true }) inputElement.addEventListener('compositionend', (e) => { isComposing = false // 此处执行输入完成后的业务逻辑 const inputValue = e.target.value }) inputElement.addEventListener('input', (e) => { // 非输入法输入状态下直接执行业务逻辑 if (!isComposing) { const inputValue = e.target.value } })
逻辑说明
compositionstart事件会在用户开始使用输入法输入复合字符(如中文、日文等需要候选的字符)时触发,此时将状态标记为输入中,忽略后续input事件的业务逻辑触发compositionend事件会在用户确认选中候选字符、完成复合输入时触发,此时将状态标记为输入完成,同时执行业务逻辑,确保拿到的是最终确认的输入值- 普通按键输入、粘贴、失焦修改等非复合输入场景不会触发
composition相关事件,input、change事件可以正常触发逻辑,覆盖所有合法输入场景 - 无需绑定原方案中的
keypress、focus、DOMAttrModified等冗余事件,上述事件组合已覆盖所有输入场景
内容的提问来源于stack exchange,提问作者shenkwen
相关产品推荐
相关产品推荐

