为 Typecho的代码块添加Copy按钮

由于目前我用的是Mirages主题,所以接下来的步骤也按这个主题来,当然主题不同,也只是改的地方不一样而已,相信这都不是事,要是真有事了欢迎留言哈。

  • 先将以下代码添加到主题header.php中的</head>标签前,或前往控制台-设置外观-主题自定义扩展(考虑到以后更新主题能够更加偷懒,建议还是放到自定义扩展中,将它添加到自定义 HTML 元素拓展-标签: head 头部 (meta 元素后)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<script>
// 在代码块右上角添加复制按钮
document.addEventListener('DOMContentLoaded', initCodeCopyButton);
function initCodeCopyButton() {
function initCSS(callback) {
const css = `
.btn-code-copy {
position: absolute;
line-height: .6em;
top: .2em;
right: .2em;
color: rgb(87, 87, 87);
}
.btn-code-copy:hover {
color: rgb(145, 145, 145);
cursor: pointer;
}
`;
const styleId = btoa('btn-code-copy').replace(/[=+\/]/g, '');
const head = document.getElementsByTagName('head')[0];
if (!head.querySelector('#' + styleId)) {
const style = document.createElement('style');
style.id = styleId;
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
}
callback();
};
function copyTextContent(source) {
let result = false;
const target = document.createElement('pre');
target.style.opacity = '0';
target.textContent = source.textContent;
document.body.appendChild(target);
try {
const range = document.createRange();
range.selectNode(target);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
result = true;
} catch (e) { console.log('copy failed.'); }
document.body.removeChild(target);
return result;
};
function initButton(pre) {
const code = pre.querySelector('code');
if (code) {
const preParent = pre.parentElement;
const newPreParent = document.createElement('div');
newPreParent.style = 'position: relative';
preParent.insertBefore(newPreParent, pre);
const copyBtn = document.createElement('div');
copyBtn.innerHTML = 'copy';
copyBtn.className = 'btn-code-copy';
copyBtn.addEventListener('click', () => {
copyBtn.innerHTML = copyTextContent(code) ? 'success' : 'failure';
setTimeout(() => copyBtn.innerHTML = 'copy', 250);
});
newPreParent.appendChild(copyBtn);
newPreParent.appendChild(pre);
}
};
const pres = document.querySelectorAll('pre');
if (pres.length !== 0) {
initCSS(() => pres.forEach(pre => initButton(pre)));
}
};
</script>
  • 如果像我一样用的是Mirages主题,那么还要交前面的代码部分修改,要不然会出现提示拷贝成功,粘贴里却是啥也没有的尴尬情况,具体为:将上述代码第35行的const target = document.createElement('pre');改成const target = document.createElement('textarea');

如果你开启了PJAX,则需单独加入回调函数。对于本主题,依次进入控制台 - 外观 - 设置外观 - PJAX(BETA) - PJAX RELOAD,将initCodeCopyButton();添加进入即可。

本文部分内容转载自 LOGI ,如果你有缘看到这篇文章,也去踩踩他的博客吧。

  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!

请我喝杯咖啡吧~

支付宝
微信