JavaScript富文本编辑器核心是contenteditable配合Selection/Range API或execCommand;主流方案基于可编辑区域+事件监听+DOM操作;推荐Tiptap、Quill或Slate等成熟库而非手写。
JavaScript 实现富文本编辑器的核心是利用浏览器原生的 contenteditable 属性配合 document.execCommand()(已废弃但仍有兼容性)或现代的 /
SelectionRange API + 自定义命令系统。目前主流方案多基于可编辑区域 + 事件监听 + DOM 操作,再封装成统一 API。
只需一个带 contenteditable="true" 的容器元素,就能获得基本编辑能力:
document.getElementById('editor').innerHTML 读取或设置内容input、selectionchange 等事件来响应格式变化成熟编辑器通常提供以下几类核心 API:
editor.getHTML()、editor.setContent(html))editor.insertNode(node)、editor.deleteSelection())editor.format('bold')、editor.toggleList('ordered'))在 contenteditable 元素上执行格式命令(兼容旧版,新项目建议用 execCommand 替代方案或直接操作 DOM):
document.execCommand('bold', false, null) —— 加粗选中文本document.execCommand('insertUnorderedList', false, null) —— 插入无序列表document.execCommand('createLink', false, 'https://example.com') —— 创建链接execCommand 已被标准弃用,Chrome 97+ 默认禁用部分命令,生产环境推荐用 Selection + Range 手动包裹节点从零手写完整富文本编辑器成本高、兼容性差,实际项目中更推荐:
contenteditable + 基础 toolbar