为 Typecho 代码框添加复制按钮
于 发布于分类: 默认 | 阅:75
很简单又很实用的一个功能,大概是因为我很久没有用鼠标了,一直用的是Mac触控板,篇幅稍微长一点的代码,用触控板滑动始终没有鼠标滑动来的方便,干脆加入一个代码框复制按钮了。
引入 JS 代码
<script>
// 在代码块右上角添加复制按钮
document.addEventListener('DOMContentLoaded', initCodeCopyButton);
function initCodeCopyButton() {
function initCSS(callback) {
const css = `
.btn-code-copy {
position: absolute;
line-height: 1.0em;
top: .5em;
right: .5em;
padding: 0.25em 0.75em;
font-size: 0.8em;
color: #333;
background-color: #f0f0f0;
border-radius: 4px;
border: 1px solid #ddd;
transition: all 0.2s ease;
}
.btn-code-copy:hover {
color: #000;
background-color: #e0e0e0;
border-color: #bbb;
cursor: pointer;
}
.btn-code-copy.success {
background-color: #4CAF50;
color: white;
border-color: #45a049;
}
.btn-code-copy.failure {
background-color: #f44336;
color: white;
border-color: #d32f2f;
}
`;
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('复制失败'); }
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 = '复制';
copyBtn.className = 'btn-code-copy';
copyBtn.addEventListener('click', () => {
const success = copyTextContent(code);
// 添加状态类并修改文本
copyBtn.className = `btn-code-copy ${success ? 'success' : 'failure'}`;
copyBtn.innerHTML = success ? '已复制!' : '复制失败';
// 恢复原始状态
setTimeout(() => {
copyBtn.className = 'btn-code-copy';
copyBtn.innerHTML = '复制';
}, 2000);
});
newPreParent.appendChild(copyBtn);
newPreParent.appendChild(pre);
}
};
const pres = document.querySelectorAll('pre');
if (pres.length !== 0) {
initCSS(() => pres.forEach(pre => initButton(pre)));
}
};
</script>将以上 JS 放在主题文件 header 或 footer 中,我是直接放在了 Post 中,因为其他地方我调用不到代码框,根据需求自选,完毕,就是这么简单,按钮样式可以自己修改。🤗