分步解决方案:
1. 推荐免费开源Markdown库
推荐使用 markdown-it(MIT协议)
特点:轻量级(15KB)、扩展性强、支持CommonMark规范、中文文档丰富
2. Markdown转HTML使用示例
html
<!DOCTYPE html> <html> <body> <!-- 引入库 --> <script src="https://cdn.jsdelivr.net/npm/markdown-it@13.0.1/dist/markdown-it.min.js"></script> <textarea id="mdInput" style="width:400px;height:200px;"> ## 标题 - 列表项 **加粗文本** </textarea> <button οnclick="convert()">转换</button> <div id="output"></div> <script> function convert() { const md = window.markdownit(); const result = md.render(document.getElementById('mdInput').value); document.getElementById('output').innerHTML = result; } </script> </body> </html>
3. UEditor添加自定义按钮
在编辑器初始化代码中添加:
javascript
UE.registerUI('mdbtn', function(editor) { const btn = new UE.UI.Button({ name: 'markdown', title: '插入Markdown', cssRules: 'background-position: -380px 0;', onclick: function() { // 这里触发弹窗显示 showMDDialog(editor); } }); return btn; }, 0 /* 按钮位置 */);
4. 弹窗实现方案
在页面添加样式和DOM:
css
#mdModal { display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%,-50%); background: white; padding: 20px; box-shadow: 0 0 10px rgba(0,0,0,0.3); z-index: 10000; } #mdOverlay { position: fixed; top:0; left:0; width:100%; height:100%; background: rgba(0,0,0,0.5); z-index: 9999; }
添加弹窗HTML结构:
html
<div id="mdOverlay" style="display:none;"></div> <div id="mdModal"> <textarea id="mdContent" style="width:500px;height:300px;"></textarea> <div style="margin-top:10px;"> <button οnclick="insertMarkdown()">确定</button> <button οnclick="closeMDDialog()">关闭</button> </div> </div>
弹窗控制逻辑:
javascript
let currentEditor = null; function showMDDialog(editor) { currentEditor = editor; document.getElementById('mdModal').style.display = 'block'; document.getElementById('mdOverlay').style.display = 'block'; } function closeMDDialog() { document.getElementById('mdModal').style.display = 'none'; document.getElementById('mdOverlay').style.display = 'none'; } function insertMarkdown() { const md = window.markdownit(); const html = md.render(document.getElementById('mdContent').value); currentEditor.execCommand('insertHtml', html); closeMDDialog(); }
整合注意事项
按顺序加载资源:先加载markdown-it,再加载UEditor
样式优化:可根据需要调整弹窗尺寸和按钮样式
安全建议:如果用于生产环境,建议添加XSS过滤
扩展建议:可添加实时预览功能,通过监听textarea的input事件实现
以上方案可实现:点击工具栏Markdown按钮 → 弹出编辑窗口 → 输入内容 → 自动转换并插入到编辑器光标位置。