---
title: "Input Events Level 2:beforeinput 与输入法合成事件"
keywords:
- beforeinput
- inputType
- compositionstart
- compositionend
- 编辑器
description: "介绍 Input Events Level 2 的 beforeinput 与 input 扩展、inputType 枚举、与 IME 合成事件协作,构建可靠的富文本与代码编辑器输入模型。"
categories:
- 应用软件
- 输入法
---
概述
beforeinput 在变更生效前触发并携带 inputType,可用于阻止或改写输入;与 compositionstart/update/end 配合处理输入法(IME)合成过程,避免误截断与错误撤销栈。
示例
const editor = document.getElementById('editor')
editor.addEventListener('beforeinput', e => {
if (e.inputType === 'insertFromPaste') {
e.preventDefault()
const text = (e.dataTransfer?.getData('text/plain') ?? e.data ?? '').trim()
insertPlainText(text)
}
})
editor.addEventListener('compositionstart', () => startIME())
editor.addEventListener('compositionend', e => commitIME(e.data))
工程建议
- 输入语义:基于
inputType构建撤销/重做与格式化;避免仅依赖键盘事件。 - IME 兼容:在合成期间避免破坏文本节点;与分词/高亮协作。
- 无障碍与性能:保持可编辑元素语义;在高频事件中最小化重排与复制。
参考与验证
- MDN beforeinput 文档:https://developer.mozilla.org/docs/Web/API/Element/beforeinput_event
- W3C Input Events Level 2:https://www.w3.org/TR/input-events-2/

发表评论 取消回复