← 中文资源

简体中文版本

compositionend 提交输入法文本

输入法组合期间 compositionupdate 只是草稿:compositionend 才携带提交后的最终文本,校验逻辑应跳过草稿、只对提交后的值做检查。

阅读英文原文

实现说明

顶层就这几处状态:input。

使用要点

  • 浏览器才是这里的运行环境:document 在 Node 里拿不到。
  • 守卫 input.dataset.composing === 'true' 满足时靠提前的 return 短路流程。
  • 直接运行文件,输出会带上标签,比如 composing started、draft:、committed:——输出的每一行都能指回产生它的那次调用。

常见问题

「compositionend 提交输入法文本」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。

核心语句

input.addEventListener('compositionupdate', (event) => {
  console.log('draft:', event.data);
});
input.addEventListener('compositionend', (event) => {
  input.dataset.composing = 'false';
  console.log('committed:', event.data);
});
input.addEventListener('compositionstart', () => {
  input.dataset.composing = 'true';
  console.log('composing started');
});

代码示例

// IME composition: the input holds in-progress text until the IME commits
const input = document.querySelector('#name');

input.addEventListener('compositionstart', () => {
  input.dataset.composing = 'true';
  console.log('composing started');
});

input.addEventListener('compositionupdate', (event) => {
  console.log('draft:', event.data);
});

// compositionend fires with the committed string before the final input event
input.addEventListener('compositionend', (event) => {
  input.dataset.composing = 'false';
  console.log('committed:', event.data);
});

input.addEventListener('input', () => {
  // Skip partial IME drafts: only committed text is validated
  if (input.dataset.composing === 'true') return;
  console.log('validated:', input.value.length, 'chars');
});