Hexo 为代码块添加复制功能按钮
本文详细记录如何在 Hexo 中为代码块添加一个 “复制” 按钮,实现一键复制代码功能。
项目地址:https://github.com/EvannZhongg/Blog-Learning.git
结构要求与适配说明
本复制功能脚本适用于以下结构的代码块:
1 2 3 4 5 6 7 8
| <figure class="highlight"> <table> <tr> <td class="gutter">...</td> <td class="code"><pre><code>...</code></pre></td> </tr> </table> </figure>
|
这是 Hexo 中多数主题(包括 Chic、NexT、Butterfly 等)默认的代码块渲染结构。
如何检查自己主题的结构是否符合?
- 启动本地博客:
hexo s
- 在浏览器中打开博客页面
- 右键代码块 → 点击“检查”
- 查看代码块的外层 HTML 标签是否为
figure.highlight
- 或者直接在浏览器中点击
F12
,在 Elements
中直接搜索是否含有 figure.highlight
1. 创建 JavaScript 脚本文件
在 Hexo 博客项目的根目录下创建 JS 脚本文件 code-copy.js
,如果没有js文件夹则自己创建:
并填入以下完整内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('figure.highlight').forEach((figure) => { if (figure.querySelector('.copy-btn')) return;
const copyBtn = document.createElement('button'); copyBtn.className = 'copy-btn'; copyBtn.title = '复制';
const copyIcon = ` <svg xmlns="http://www.w3.org/2000/svg" height="14" width="15" viewBox="0 0 24 24" fill="white"> <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 18H8V7h11v16z"/> </svg> `;
const checkIcon = ` <svg xmlns="http://www.w3.org/2000/svg" height="14" width="15" viewBox="0 0 24 24" fill="#00cc66"> <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/> </svg> `;
copyBtn.innerHTML = copyIcon;
Object.assign(copyBtn.style, { position: 'absolute', top: '8px', right: '8px', padding: '4px', background: '#aaa', border: 'none', borderRadius: '4px', cursor: 'pointer', opacity: '0.85', zIndex: 1000, transition: 'opacity 0.2s ease', boxShadow: '0 1px 3px rgba(0, 0, 0, 0.15)' });
copyBtn.addEventListener('mouseover', () => copyBtn.style.opacity = '1'); copyBtn.addEventListener('mouseout', () => copyBtn.style.opacity = '0.85');
copyBtn.addEventListener('click', () => { const code = figure.querySelector('td.code'); const text = code ? code.innerText : ''; navigator.clipboard.writeText(text).then(() => { copyBtn.innerHTML = checkIcon; setTimeout(() => { copyBtn.innerHTML = copyIcon; }, 1000); }); });
figure.style.position = 'relative'; figure.appendChild(copyBtn); }); });
|
2. 在页面底部引入 JS 文件
打开文件:
1
| themes/hexo-theme-Chic/layout/_partial/footer.ejs
|
在 </footer>
标签之后添加以下代码:
1
| <script src="/js/code-copy.js"></script>
|
这样可以确保复制按钮脚本在页面加载完毕后自动运行。
3. 生成并本地预览效果
运行以下命令,重新生成并启动本地预览:
1 2 3
| hexo clean hexo g hexo d
|
然后访问 http://localhost:4000
,查看任意一段代码块,右上角应出现复制图标按钮。
修改后的相关完整代码可以在文章开头的项目地址中获取
该项目代码基于 Hexo 和 hexo-theme-Chic 。