为了实现从 DeepSeek 等外部直接复制富文本内容并保留原有样式,需要修改两处:
编辑器(micro-editor.js):允许粘贴 HTML 并保留格式。
前台显示样式(style.css):确保文章内容中的标题、代码块等显示美观。
编辑器(micro-editor.js):允许粘贴 HTML 并保留格式。
前台显示样式(style.css):确保文章内容中的标题、代码块等显示美观。
一、修改编辑器粘贴行为(保留格式)
打开 assets/js/micro-editor.js,找到 bindEvents 方法中的 paste 事件监听,将其修改为:
this.editorDiv.addEventListener('paste', (e) => { e.preventDefault(); // 获取剪贴板中的 HTML 内容 let html = ''; if (e.clipboardData) { html = e.clipboardData.getData('text/html'); if (!html) { // 如果没有 HTML,则获取纯文本 html = e.clipboardData.getData('text/plain'); } } else if (window.clipboardData) { html = window.clipboardData.getData('Text'); } if (html) { // 可选:简单过滤掉 script 等危险标签 html = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, ''); html = html.replace(/ on\w+="[^"]*"/gi, ''); // 移除行内事件 // 插入 HTML document.execCommand('insertHTML', false, html); } else { // 降级:插入纯文本 const text = (e.clipboardData || window.clipboardData).getData('text/plain'); document.execCommand('insertText', false, text); } });
这样,粘贴时就会保留原 HTML 结构(标题、列表、代码块、内联样式等),同时去除了脚本和事件属性保证安全。
二、增强前台文章详情页的样式
在 assets/css/style.css 的 .article-content 区域补充以下样式,使复制的标题、代码块等显示规范:
/* 文章内容区域:保留标题样式 */ .article-content h1 { font-size: 28px; margin: 20px 0 15px; font-weight: 700; border-left: 4px solid var(--primary); padding-left: 15px; } .article-content h2 { font-size: 24px; margin: 25px 0 12px; font-weight: 600; } .article-content h3 { font-size: 20px; margin: 20px 0 10px; font-weight: 600; } .article-content h4, .article-content h5, .article-content h6 { margin: 15px 0 8px; font-weight: 500; } /* 代码块样式(与编辑器代码高亮匹配) */ .article-content pre { background: #2c3e50; color: #f8f9fa; padding: 15px; border-radius: 8px; overflow-x: auto; font-size: 14px; line-height: 1.45; margin: 20px 0; } .article-content code { font-family: 'Courier New', monospace; background: #f0f0f0; padding: 2px 6px; border-radius: 4px; font-size: 0.9em; } .article-content pre code { background: transparent; padding: 0; color: inherit; } /* 引用样式 */ .article-content blockquote { margin: 20px 0; padding: 12px 20px; background: #f8f9fa; border-left: 4px solid var(--primary); color: #555; font-style: italic; } /* 列表样式 */ .article-content ul, .article-content ol { margin: 15px 0 15px 30px; } /* 表格样式(如果复制的表格) */ .article-content table { border-collapse: collapse; width: 100%; margin: 15px 0; } .article-content th, .article-content td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; } .article-content th { background: #f2f2f2; } /* 内联样式保留(无需额外处理) */
这些样式会使标题、代码块、表格等看起来层次分明,与编辑器中的预览保持一致。
三、保存与测试
修改
micro-editor.js后,清除浏览器缓存。在后台编辑文章,复制 DeepSeek 的一段回答(包含标题、代码块等),粘贴到编辑器。
保存后,查看前台文章页,样式应完整保留。
如果某些内联样式未生效(如字体颜色、背景色),请确认前台
style.css中没有覆盖这些属性(通常不会)。若希望保留更多内联样式,可不对.article-content *做强制重置。
现在,您可以直接复制任何格式丰富的文本,无需手动排版
发表评论 (0)
留下你的足迹