Skip to content
New issue

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

第 51 期(W3C 标准-JavaScript-事件):复合事件 #54

Open
wingmeng opened this issue Jul 5, 2019 · 0 comments
Open

第 51 期(W3C 标准-JavaScript-事件):复合事件 #54

wingmeng opened this issue Jul 5, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Jul 5, 2019

使用中文输入法在搜索框中打字的时候,经常会发现一个问题:当我们还在组词选字的时候,输入框就已经触发了输入事件,把搜索结果给展示了出来,而这个时候我们的输入其实还没有结束。如下图所示:

v2-6e6632109aa8d6642289835eaa1fe7da_b


思路:

可以利用复合事件来解决这个问题:在我们开始输入法组词的时候浏览器会触发一个 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant