js 实现富文本编辑器
实现富文本编辑器的基本方法
使用JavaScript实现富文本编辑器可以通过原生API或第三方库完成。以下是几种常见方案:
使用contentEditable属性
HTML5的contentEditable属性允许将任何DOM元素变为可编辑区域:
<div id="editor" contenteditable="true"></div>
通过document.execCommand执行格式化命令:
// 加粗选中文本
document.execCommand('bold', false, null);
// 插入链接
document.execCommand('createLink', false, 'https://example.com');
使用第三方库
-
Quill.js
模块化设计,支持自定义格式:const quill = new Quill('#editor', { modules: { toolbar: true }, theme: 'snow' }); -
TinyMCE
企业级解决方案,提供插件系统:tinymce.init({ selector: '#editor', plugins: 'link image code' }); -
ProseMirror
适用于需要精细控制的场景:const editorView = new EditorView(document.querySelector("#editor"), { state: EditorState.create({ schema: basicSchema }) });
自定义实现核心功能
-
选区操作
通过window.getSelection()获取当前选区:const selection = window.getSelection(); const range = selection.getRangeAt(0); -
格式保存与恢复
使用Range对象保存选区状态:function saveSelection() { const range = window.getSelection().getRangeAt(0); return range.cloneRange(); } -
HTML净化处理
防止XSS攻击:function sanitize(html) { const temp = document.createElement('div'); temp.textContent = html; return temp.innerHTML; }
现代API方案
使用Slate.js等基于React的框架:
const initialValue = [{ type: 'paragraph', children: [{ text: '' }] }];
const editor = useMemo(() => withReact(createEditor()), []);
关键注意事项
- 跨浏览器兼容性需测试
execCommand的支持程度 - 移动端需处理虚拟键盘与编辑区的交互
- 粘贴内容时需过滤非预期HTML标签
- 撤销/重做功能需实现命令历史栈
扩展功能实现
-
图片上传
通过FileReader读取本地文件:const reader = new FileReader(); reader.onload = (e) => { document.execCommand('insertImage', false, e.target.result); }; reader.readAsDataURL(file); -
Markdown支持
转换Markdown到HTML:function markdownToHtml(md) { return marked.parse(md); } -
协同编辑
使用Operational Transformation算法:
socket.on('operation', (op) => { editor.applyOperation(op); });
以上方案可根据项目需求组合使用,轻量级场景推荐Quill.js,复杂应用建议采用ProseMirror或Slate.js架构。






