35 lines
1.0 KiB
JavaScript
35 lines
1.0 KiB
JavaScript
const MarkdownRenderer = {
|
|
init() {
|
|
// 配置 marked.js
|
|
marked.setOptions({
|
|
highlight: function(code, lang) {
|
|
if (lang && hljs.getLanguage(lang)) {
|
|
return hljs.highlight(code, { language: lang }).value;
|
|
}
|
|
return hljs.highlightAuto(code).value;
|
|
},
|
|
breaks: true,
|
|
gfm: true
|
|
});
|
|
},
|
|
|
|
render(text) {
|
|
if (!text) return '';
|
|
let html = marked.parse(text);
|
|
// 为代码块添加复制按钮
|
|
html = html.replace(/<pre><code/g, '<pre><button class="copy-btn" onclick="MarkdownRenderer.copyCode(this)">复制</button><code');
|
|
return html;
|
|
},
|
|
|
|
copyCode(btn) {
|
|
const code = btn.nextElementSibling;
|
|
navigator.clipboard.writeText(code.textContent).then(() => {
|
|
btn.textContent = '已复制';
|
|
setTimeout(() => { btn.textContent = '复制'; }, 2000);
|
|
});
|
|
}
|
|
};
|
|
|
|
// 初始化
|
|
MarkdownRenderer.init();
|