实现说明
顶层就这几处状态: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');
});