We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
使用中文输入法在搜索框中打字的时候,经常会发现一个问题:当我们还在组词选字的时候,输入框就已经触发了输入事件,把搜索结果给展示了出来,而这个时候我们的输入其实还没有结束。如下图所示:
思路:
可以利用复合事件来解决这个问题:在我们开始输入法组词的时候浏览器会触发一个 compositionstart 事件,在输入法组词结束的时候,浏览器会触发 compositionend 事件,我们可以维护一个变量表示是否正在处于组词状态,通过监听这两个事件来改变这个状态,这样就能保证在组词结束后才触发 oninput 了。
compositionstart
compositionend
oninput
参考代码:
<input type="text" id="input"> <p id="result"></p>
var input = document.getElementById('input'); var result = document.getElementById('result'); var isTyping = false; input.addEventListener('compositionstart', function() { console.log('typing...'); isTyping = true; }); input.addEventListener('compositionend', function() { console.log('typing end'); isTyping = false; output(this.value); }); input.addEventListener('input', function() { console.log('value changed'); if (isTyping) { return } // 在输入汉字的情况下这一句不会执行,因为 input 事件总是先于 compositionend output(this.value); }); function output(value) { result.innerHTML = value; }
compositionstart compositionend
The text was updated successfully, but these errors were encountered:
No branches or pull requests
使用中文输入法在搜索框中打字的时候,经常会发现一个问题:当我们还在组词选字的时候,输入框就已经触发了输入事件,把搜索结果给展示了出来,而这个时候我们的输入其实还没有结束。如下图所示:
思路:
可以利用复合事件来解决这个问题:在我们开始输入法组词的时候浏览器会触发一个
compositionstart
事件,在输入法组词结束的时候,浏览器会触发compositionend
事件,我们可以维护一个变量表示是否正在处于组词状态,通过监听这两个事件来改变这个状态,这样就能保证在组词结束后才触发oninput
了。参考代码:
The text was updated successfully, but these errors were encountered: