How to add the copy function in hexo

希望自己的博客即将保持简洁清爽 不适用更多的主题和插件实现代码框的复制功能

在hexo blog 根目录的source 下创建css 和 js文件夹并添加对应文件和代码

1
2
3
4
5
6
hh@S4IwyKR7FWTit:~/hexoblog/source$ ls
_posts css js
hh@S4IwyKR7FWTit:~/hexoblog/source$ ls css/
copy-button.css
hh@S4IwyKR7FWTit:~/hexoblog/source$ ls js/
copy-code.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
/* source/css/copy-button.css */
.highlight {
position: relative;
}

.copy-btn {
position: absolute;
top: 8px;
right: 8px;
padding: 4px 8px;
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 4px;
color: #fff;
font-size: 12px;
cursor: pointer;
opacity: 0;
transition: opacity 0.2s;
}

.highlight:hover .copy-btn {
opacity: 1;
}

.copy-btn.copied {
background: #4CAF50;
border-color: #4CAF50;
}
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
// source/js/copy-code.js
document.addEventListener('DOMContentLoaded', function() {
// 遍历所有代码块容器(默认主题中代码块外层通常有 .highlight 类)
document.querySelectorAll('.highlight').forEach(block => {
// 创建复制按钮
const btn = document.createElement('button');
btn.className = 'copy-btn';
btn.textContent = '复制';

// 添加点击事件,复制代码块内 .code pre 元素中的内容
btn.addEventListener('click', () => {
const codeEl = block.querySelector('.code pre');
if (!codeEl) {
console.error('未找到代码元素');
return;
}
const code = codeEl.innerText;
navigator.clipboard.writeText(code).then(() => {
btn.textContent = '已复制';
btn.classList.add('copied');
setTimeout(() => {
btn.textContent = '复制';
btn.classList.remove('copied');
}, 2000);
}).catch(err => {
console.error('复制失败:', err);
});
});

// 将复制按钮添加到代码块容器中
block.appendChild(btn);
});
});

在hexo blog 根目录 创建scripts目录 并添加对应文件和代码

1
2
hh@S4IwyKR7FWTit:~/hexoblog/scripts$ ls
injector.js
1
2
3
4
5
6
7
8
9
10
// scripts/injector.js
hexo.extend.injector.register(
'head_end',
'<link rel="stylesheet" href="/css/copy-button.css">'
);

hexo.extend.injector.register(
'body_end',
'<script src="/js/copy-code.js"></script>'
);

清除并重新生成hexo 的静态文件即可

1
sudo hexo clean;sudo hexo g