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

第 80 期(W3C 标准-JavaScript-事件):InputEvent.inputType #83

Open
wingmeng opened this issue Aug 7, 2019 · 0 comments
Open

第 80 期(W3C 标准-JavaScript-事件):InputEvent.inputType #83

wingmeng opened this issue Aug 7, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Aug 7, 2019

第 51 期(W3C 标准-JavaScript-事件):复合事件 中我们了解了复合事件,并利用复合事件解决了在文本框中输入中文时的提前上屏问题。本期要介绍的是 input 事件里的 inputType 属性,利用它也可以解决上面那个问题。

写过表单相关代码的同学应该对 input 事件不陌生,我们可以在 input 事件的回调函数里对输入内容进行即时处理,它的 event 参数有个 inputType 属性,会返回当前输入的类型:

  • insertText 键盘直接输入的
  • insertFromPaste 通过粘贴进来的
  • insertCompositionText 通过 IME 输入的
  • insertFromDrop 通过拖放进来的
  • deleteContentBackward 回退删除(按 backspace 键)
  • deleteContentForward 前向删除(按 delete 键)
  • deleteByCut 剪切删除(选中文本按 ctrl + X)

更多类型请参阅:https://www.w3.org/TR/input-events-1/

有了输入类型我们就可以准确判断输入来源并做相应的处理了。下面我们利用这个特性来解决上面那个中文输入时提前上屏的问题:

<input type="text" id="input">
<p id="result"></p>
var input = document.getElementById('input');
var result = document.getElementById('result');

input.addEventListener('input', function(e) {
  const inputType = e.inputType;

  if (inputType !== 'insertCompositionText') {
    output(this.value);
  }
});

input.addEventListener('compositionend', function() {
  output(this.value);
});

function output(value) {
  result.innerHTML = 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