js实现编辑
使用 JavaScript 实现编辑功能
基础文本编辑
通过 contenteditable 属性实现简单的文本编辑功能:
<div id="editable" contenteditable="true">点击编辑文本</div>
监听内容变化:
document.getElementById('editable').addEventListener('input', function(e) {
console.log('新内容:', e.target.innerHTML);
});
表单输入编辑
创建可编辑的表单输入框:
<input type="text" id="textInput" value="可编辑文本">
<button id="saveBtn">保存</button>
处理编辑和保存:
document.getElementById('saveBtn').addEventListener('click', function() {
const newValue = document.getElementById('textInput').value;
console.log('保存的内容:', newValue);
});
富文本编辑器实现
使用 document.execCommand 实现基本富文本功能:
<div id="editor" contenteditable="true"></div>
<button onclick="formatText('bold')">加粗</button>
<button onclick="formatText('italic')">斜体</button>
实现格式化函数:
function formatText(command) {
document.execCommand(command, false, null);
}
使用第三方库
引入 CKEditor 等专业编辑器库:
<script src="https://cdn.ckeditor.com/ckeditor5/36.0.1/classic/ckeditor.js"></script>
<textarea id="editor"></textarea>
初始化编辑器:
ClassicEditor
.create(document.querySelector('#editor'))
.catch(error => {
console.error(error);
});
实现撤销/重做功能
维护编辑历史记录:
const editor = document.getElementById('editable');
let history = [];
let historyIndex = -1;
editor.addEventListener('input', function() {
history = history.slice(0, historyIndex + 1);
history.push(editor.innerHTML);
historyIndex++;
});
function undo() {
if (historyIndex > 0) {
historyIndex--;
editor.innerHTML = history[historyIndex];
}
}
function redo() {
if (historyIndex < history.length - 1) {
historyIndex++;
editor.innerHTML = history[historyIndex];
}
}
保存编辑内容
将编辑内容保存到本地存储:

function saveContent() {
const content = document.getElementById('editable').innerHTML;
localStorage.setItem('savedContent', content);
}
function loadContent() {
const saved = localStorage.getItem('savedContent');
if (saved) {
document.getElementById('editable').innerHTML = saved;
}
}






