Trilum 共享页面添加代码块复制功能
方案#
- 保留原始 EJS 模板内容不动。
- 在
</body>前插入 一段 script + style,只处理<pre><code>的 Copy 按钮。 - 不动任何头部 JS、BackTop、行号或滚动逻辑。
插入代码示例#
[ding@ArchLinux templates]$ cp page.ejs page.ejs_$(date +%Y%m%d%H%M%S)
[ding@ArchLinux templates]$ ls
404.ejs page.ejs page.ejs_20260306152523 page.ejs-bak202603061428 prev_next.ejs toc_item.ejs tree_item.ejs
[ding@ArchLinux templates]$ pwd
/opt/trilium/share-theme/templates在你模板文件page.ejs中找到这一行:
<%- renderSnippets("body:end") %>就在它之前插入:
<script>
document.addEventListener("DOMContentLoaded", function () {
document.querySelectorAll("pre code").forEach((block) => {
const pre = block.parentElement;
pre.style.position = "relative";
// 创建 Copy 按钮
const btn = document.createElement("button");
btn.className = "copy-btn";
btn.innerText = "Copy";
btn.addEventListener("click", () => {
navigator.clipboard.writeText(block.textContent);
btn.innerText = "Copied!";
setTimeout(() => btn.innerText = "Copy", 1500);
});
// 自动隐藏按钮
btn.style.opacity = "0";
btn.style.transition = "0.2s";
pre.addEventListener("mouseenter", () => btn.style.opacity = "0.9");
pre.addEventListener("mouseleave", () => btn.style.opacity = "0");
pre.appendChild(btn);
});
});
</script>
<style>
pre { position: relative; overflow-x: auto; }
pre .copy-btn {
position: absolute;
top: 4px;
right: 4px;
font-size: 12px;
padding: 2px 6px;
border: none;
border-radius: 4px;
background: #444;
color: #fff;
cursor: pointer;
}
</style>✅ 说明:
- 不改动任何原来的 JS 或 CSS,所以不会破坏行号、BackTop、主题切换等。
- Copy 按钮只显示在鼠标悬浮
<pre>时。 - 点击会自动复制代码内容并提示 “Copied!”。
- 兼容所有 Trilium 原始模板,无 async/await 问题。