如何基于INPUT EVENTS LEVEL 2实现WYSIWYG富文本编辑器?
基于INPUT EVENTS LEVEL 2实现WYSIWYG编辑器
核心思路
INPUT EVENTS LEVEL 2 并非直接替代Document.execCommand的命令式API,而是通过监听输入事件(beforeinput、input),配合Selection API和Range API直接操作DOM,实现富文本编辑逻辑,完全掌控编辑行为。
1. 搭建基础编辑器容器
先创建一个可编辑的DOM元素作为编辑器核心:
<div id="editor" contenteditable="true" style="border:1px solid #eee; padding:12px; min-height:240px;"></div>
2. 拦截输入事件
利用beforeinput事件拦截浏览器默认编辑行为,自定义处理逻辑:
const editor = document.getElementById('editor'); editor.addEventListener('beforeinput', (e) => { e.preventDefault(); // 阻止默认行为,由自己处理 handleEditorInput(e.inputType, e.data); });
3. 实现富文本格式操作(以加粗为例)
通过Selection和RangeAPI操作选区和DOM:
function handleEditorInput(inputType, data) { // 处理加粗操作 if (inputType === 'formatBold') { const selection = window.getSelection(); if (!selection.rangeCount) return; const range = selection.getRangeAt(0); if (range.collapsed) { // 无选中内容:插入空的加粗标签并定位光标 const boldEl = document.createElement('strong'); range.insertNode(boldEl); // 将光标移至加粗标签内 const newRange = document.createRange(); newRange.selectNodeContents(boldEl); newRange.collapse(true); selection.removeAllRanges(); selection.addRange(newRange); } else { // 有选中内容:用加粗标签包裹选区 const boldEl = document.createElement('strong'); try { range.surroundContents(boldEl); } catch (err) { // 处理跨节点选区的兼容情况 const fragment = range.extractContents(); boldEl.appendChild(fragment); range.insertNode(boldEl); } } return; } // 处理普通文本输入 if (inputType === 'insertText') { const selection = window.getSelection(); if (!selection.rangeCount) return; const range = selection.getRangeAt(0); range.deleteContents(); // 清除选区内容(如果有选中) const textNode = document.createTextNode(data); range.insertNode(textNode); // 将光标移至输入文本后方 range.setStartAfter(textNode); range.collapse(true); selection.removeAllRanges(); selection.addRange(range); } // 其他格式操作(斜体、下划线、有序列表等)逻辑类似,替换对应标签即可 }
4. 关键API说明
window.getSelection():获取当前用户的选区对象Range API:用于精确操作DOM范围,支持插入、删除、包裹节点等操作beforeinput.inputType:标识触发的输入类型,常见值包括formatBold、formatItalic、insertText、deleteContentBackward等
内容的提问来源于stack exchange,提问作者COLONEL FF
相关产品推荐
相关产品推荐

