js实现编辑
JavaScript 实现文本编辑功能
使用 contenteditable 属性可以让 HTML 元素变为可编辑状态。以下是一个简单的实现示例:
<div id="editor" contenteditable="true">点击这里开始编辑</div>
获取和设置编辑内容
通过 JavaScript 可以轻松获取和设置可编辑区域的内容:
const editor = document.getElementById('editor');
// 获取内容
const content = editor.innerHTML;
// 设置内容
editor.innerHTML = '<strong>新内容</strong>';
实现富文本编辑功能
使用 document.execCommand 可以实现基本的富文本编辑功能,虽然这个 API 已废弃,但在许多浏览器中仍然可用:
function formatText(command, value = null) {
document.execCommand(command, false, value);
}
现代替代方案
推荐使用更现代的库如 ProseMirror 或 Tiptap 来实现富文本编辑:
import { Editor } from 'tiptap';
new Editor({
element: document.getElementById('editor'),
content: '<p>初始内容</p>',
});
处理编辑事件
监听输入事件可以实时获取编辑内容:
editor.addEventListener('input', (e) => {
console.log('内容已更改:', e.target.innerHTML);
});
保存编辑内容
可以将编辑内容保存到本地存储或发送到服务器:
function saveContent() {
localStorage.setItem('editorContent', editor.innerHTML);
// 或使用 fetch 发送到服务器
}
实现撤销/重做功能
维护一个编辑历史数组可以实现简单的撤销功能:
let history = [];
let historyIndex = -1;
editor.addEventListener('input', () => {
history = history.slice(0, historyIndex + 1);
history.push(editor.innerHTML);
historyIndex++;
});
function undo() {
if (historyIndex > 0) {
historyIndex--;
editor.innerHTML = history[historyIndex];
}
}






