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

中文输入法的救星 composition event #23

Open
brunoyang opened this issue Dec 17, 2017 · 0 comments
Open

中文输入法的救星 composition event #23

brunoyang opened this issue Dec 17, 2017 · 0 comments

Comments

@brunoyang
Copy link
Owner

最近在工作中碰到搜索的需求,需要实时获取输入框中的内容并请求搜索结果,一开始想到的就是用input事件监听,在英文输入的情况下一切 ok,但在使用中文输入法时就会出现问题了。比如输入 a、s、d三个字符,我们想要的情况是输入时不触发 input 事件,在选择好对应的中文字符后再触发。而实际情况是每按下一次键盘后都会触发一次 input 事件然后去请求了接口,这显然不是我想要的,一番查找之后,终于找到了解决方案。

人民大救星 composition event

composition event可以观察用户在输入法中组字选词的状态。composition event提供三个事件,分别为compositionstart compositionupdate compositionend

  • compositionstart:开始通过输入法输入法输入字符时触发,当实现选中了某些字符才开始输入时,事件对象的data属性就是这些字符,否则为空字符串;
  • compositionupdate:输入字符时触发,事件对象的data属性的值为输入的字符,该事件用得比较少;
  • compositionend:结束选词时触发,事件对象的data属性的值为选中的词;

compositionend事件会在input事件之后触发,所以需要在compositionend事件中手动执行input事件的处理逻辑。

实现需求

结合 compositionstartcompositionendinput事件就可以实现我们的需求

const input = document.querySelector('input');
let inputLocked = false;

input.addEventListender('compositionstart', () => {
  inputLocked = true;
});

input.addEventListener('compositionend', () => {
  inputLocked = false;
});

input.addEventListener('input', () => {
  if (!inputLocked) {
    console.log(input.value);
  }
});
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