WordPress文章 添加代码复制按钮的方法
本文章实现WordPress文章 添加代码复制按钮的方法
不懂的可以评论或联系我邮箱:owen@owenzhang.com
著作权归OwenZhang所有。商业转载请联系OwenZhang获得授权,非商业转载请注明出处。
注意
注意,主题更新后,主题内的文件内容就会失效,得重新添加
主题内footer.php
文件目录:
/www/wwwroot/owenblog-wordpress/wp-content/themes/personal-cv-resume/footer.php
添加一下代码:
<style>
.copy-btn {
float: right;
opacity: 0.5;
color: white !important;
display: block;
padding: 3px 8px;
background-color: #333 !important;
border: 1px solid hsla(0, 0%, 6%, .95) !important;
}
</style>
<style>
.copy-btn {
float: right;
opacity: 0.5;
color: white !important;
display: block;
padding: 3px 8px;
background-color: #333 !important;
border: 1px solid hsla(0, 0%, 6%, .95) !important;
}
</style>
<script>
document.querySelectorAll('pre').forEach(pre => {
const button = document.createElement('button');
button.className = 'copy-btn';
button.textContent = 'Copy';
button.addEventListener('click', () => {
const code = pre.querySelector('code');
const textToCopy = code ? code.innerText : pre.innerText.replace(button.textContent, '');
navigator.clipboard.writeText(textToCopy);
button.textContent = 'Copied!';
setTimeout(() => button.textContent = 'Copy', 2000);
});
pre.style.position = 'relative';
pre.prepend(button);
});
</script>
效果图

Buy me a cup of coffee :)
觉得对你有帮助,就给我打赏吧,谢谢!






用户今天 : 19
合计查看 : 16018
谁是在线的 : 1
你的IP地址 : 40.77.167.30