Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

第 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;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.