js实现编辑器
实现基础文本编辑器
使用HTML的contenteditable属性创建可编辑区域
<div id="editor" contenteditable="true"></div>
添加基本样式使编辑器更明显
#editor {
min-height: 200px;
border: 1px solid #ccc;
padding: 10px;
}
添加格式控制按钮
创建格式工具栏HTML结构
<div class="toolbar">
<button onclick="formatText('bold')">B</button>
<button onclick="formatText('italic')">I</button>
<button onclick="formatText('underline')">U</button>
</div>
实现格式控制函数
function formatText(command) {
document.execCommand(command, false, null);
}
支持更多编辑功能
添加列表和对齐功能按钮

<button onclick="formatText('insertUnorderedList')">无序列表</button>
<button onclick="formatText('insertOrderedList')">有序列表</button>
<button onclick="formatText('justifyLeft')">左对齐</button>
<button onclick="formatText('justifyCenter')">居中</button>
实现内容保存与加载
保存编辑器内容
function saveContent() {
const content = document.getElementById('editor').innerHTML;
localStorage.setItem('editorContent', content);
}
加载保存的内容
function loadContent() {
const savedContent = localStorage.getItem('editorContent');
if(savedContent) {
document.getElementById('editor').innerHTML = savedContent;
}
}
添加Markdown支持
使用marked.js库转换Markdown

function renderMarkdown() {
const markdownText = document.getElementById('editor').textContent;
const html = marked.parse(markdownText);
document.getElementById('editor').innerHTML = html;
}
实现图片上传功能
创建文件输入元素
<input type="file" id="imageUpload" accept="image/*" style="display:none">
<button onclick="document.getElementById('imageUpload').click()">插入图片</button>
处理图片上传
document.getElementById('imageUpload').addEventListener('change', function(e) {
const file = e.target.files[0];
if(file) {
const reader = new FileReader();
reader.onload = function(event) {
document.execCommand('insertImage', false, event.target.result);
};
reader.readAsDataURL(file);
}
});
添加撤销重做功能
维护编辑历史栈
let history = [];
let historyIndex = -1;
document.getElementById('editor').addEventListener('input', function() {
history = history.slice(0, historyIndex + 1);
history.push(this.innerHTML);
historyIndex++;
});
实现撤销和重做函数
function undo() {
if(historyIndex > 0) {
historyIndex--;
document.getElementById('editor').innerHTML = history[historyIndex];
}
}
function redo() {
if(historyIndex < history.length - 1) {
historyIndex++;
document.getElementById('editor').innerHTML = history[historyIndex];
}
}






