js实现编辑器
实现基础文本编辑器
使用HTML的contenteditable属性创建可编辑区域
<div id="editor" contenteditable="true"></div>
添加基本样式确保可见性
#editor {
min-height: 200px;
border: 1px solid #ccc;
padding: 10px;
}
添加格式控制按钮
创建格式工具栏
<div class="toolbar">
<button onclick="formatText('bold')">加粗</button>
<button onclick="formatText('italic')">斜体</button>
<button onclick="formatText('underline')">下划线</button>
</div>
实现格式控制函数
function formatText(command) {
document.execCommand(command, false, null);
}
支持自定义快捷键
监听键盘事件实现快捷键
document.getElementById('editor').addEventListener('keydown', function(e) {
if (e.ctrlKey && e.key === 'b') {
e.preventDefault();
formatText('bold');
}
});
实现撤销/重做功能
维护操作历史栈
let history = [];
let historyIndex = -1;
function saveState() {
const content = document.getElementById('editor').innerHTML;
history = history.slice(0, historyIndex + 1);
history.push(content);
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];
}
}
集成Markdown支持
添加Markdown解析库
// 使用marked.js库
function renderMarkdown() {
const markdownText = document.getElementById('editor').textContent;
document.getElementById('editor').innerHTML = marked.parse(markdownText);
}
实现自动保存功能
设置定时保存
setInterval(() => {
localStorage.setItem('editorContent', document.getElementById('editor').innerHTML);
}, 5000);
// 页面加载时恢复内容
window.onload = function() {
const savedContent = localStorage.getItem('editorContent');
if (savedContent) {
document.getElementById('editor').innerHTML = savedContent;
}
};
添加图片上传功能
实现文件选择处理
function insertImage() {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.onchange = e => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = event => {
const img = document.createElement('img');
img.src = event.target.result;
document.getElementById('editor').appendChild(img);
};
reader.readAsDataURL(file);
};
input.click();
}
实现代码块支持
添加语法高亮功能
function insertCodeBlock() {
const code = prompt('输入代码:');
if (code) {
const pre = document.createElement('pre');
const codeElement = document.createElement('code');
codeElement.textContent = code;
pre.appendChild(codeElement);
document.getElementById('editor').appendChild(pre);
hljs.highlightElement(codeElement); // 使用highlight.js
}
}
响应式设计优化
添加媒体查询适应不同设备
@media (max-width: 768px) {
#editor {
min-height: 150px;
font-size: 14px;
}
.toolbar button {
padding: 5px;
font-size: 12px;
}
}






