js实现文本编辑器
实现基础文本编辑器
使用contenteditable属性创建可编辑区域是最简单的方式。通过设置HTML元素的contenteditable="true",可以让任何元素变成可编辑状态。
<div id="editor" contenteditable="true"></div>
添加基础样式增强编辑体验:
#editor {
min-height: 200px;
border: 1px solid #ccc;
padding: 10px;
outline: none;
}
添加格式控制按钮
创建工具栏按钮来控制文本格式,使用document.execCommand执行格式化命令:
<div class="toolbar">
<button onclick="formatText('bold')">加粗</button>
<button onclick="formatText('italic')">斜体</button>
<button onclick="formatText('underline')">下划线</button>
</div>
<script>
function formatText(command) {
document.execCommand(command, false, null);
}
</script>
实现选区保持
在修改编辑器内容时保持当前选区:
function saveSelection() {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
return range;
}
function restoreSelection(range) {
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
支持更多格式选项
扩展execCommand支持的其他格式操作:
function setFontSize(size) {
document.execCommand('fontSize', false, '7');
const fontElements = document.getElementsByTagName('font');
for (let i = 0; i < fontElements.length; i++) {
if (fontElements[i].size === '7') {
fontElements[i].removeAttribute('size');
fontElements[i].style.fontSize = size + 'px';
}
}
}
实现撤销/重做功能
使用document.execCommand的撤销和重做命令:
function undo() {
document.execCommand('undo', false, null);
}
function redo() {
document.execCommand('redo', false, null);
}
使用自定义数据存储
对于更复杂的编辑器,可以使用自定义数据结构存储内容:
class EditorState {
constructor(content, selection) {
this.content = content;
this.selection = selection;
}
}
class EditorHistory {
constructor() {
this.states = [];
this.currentIndex = -1;
}
pushState(state) {
this.states = this.states.slice(0, this.currentIndex + 1);
this.states.push(state);
this.currentIndex++;
}
}
实现现代编辑器方案
对于生产环境,推荐使用专业库如:
- ProseMirror
- Tiptap
- Slate.js
- Quill
- CKEditor
这些库提供了更完整的解决方案,包括协作编辑、插件系统等高级功能。
处理粘贴内容
清理粘贴的HTML内容:
document.getElementById('editor').addEventListener('paste', (e) => {
e.preventDefault();
const text = (e.clipboardData || window.clipboardData).getData('text/plain');
document.execCommand('insertText', false, text);
});
添加Markdown支持
将Markdown转换为HTML:
function markdownToHtml(markdown) {
// 简单替换实现
return markdown
.replace(/^# (.*$)/gm, '<h1>$1</h1>')
.replace(/^## (.*$)/gm, '<h2>$1</h2>')
.replace(/\*\*(.*)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.*)\*/g, '<em>$1</em>');
}
实现自动保存
定时保存编辑器内容:

setInterval(() => {
const content = document.getElementById('editor').innerHTML;
localStorage.setItem('editorContent', content);
}, 5000);






