对于长期使用wordpress编写IT类博客的博主来说,一定会经常在博客文章中填写部分代码或者命令行,如果在代码代码命令行的后面有一个小小的“复制代码”的按钮,对于阅读文章的人来说是非常方便的,然而wordpress默认的代码块却没有这个按钮功能。
不过没问题,我给大家提供一个非常简单的办法来解决这个问题。
在您编写需要显示代码的文章的时候,在文章的任何位置另外添加一个html块,并且将下面的这段javascript代码复制到这个html当中。保存你的文章之后,代码块的右上角就会显示一个“复制代码”按钮了,而下面这段代码并不会在你的文章中显示出来,这样就可以完美解决这个问题了,就像你可以在下面的代码框中看到的一样。
<script>
document.addEventListener('DOMContentLoaded', function() {
var codeBlocks = document.querySelectorAll('.wp-block-code');
codeBlocks.forEach(function(block) {
var code = block.querySelector('code');
var button = document.createElement('button');
var buttonText = document.createTextNode('复制代码');
button.appendChild(buttonText);
button.style.cssText = 'position: absolute; top: 0; right: 0; margin: 4px; padding: 4px 8px; font-size: 12px; background-color: rgba(0, 0, 0, 0.2); color: #fff; border: none; border-radius: 4px; cursor: pointer; transition: all 0.2s ease-in-out;';
button.addEventListener('mouseenter', function() {
button.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
});
button.addEventListener('mouseleave', function() {
button.style.backgroundColor = 'rgba(0, 0, 0, 0.3)';
});
button.addEventListener('click', function() {
var range = document.createRange();
range.selectNode(code);
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
button.innerText = '已复制';
button.style.backgroundColor = '#333';
button.style.color = '#fff';
setTimeout(function() {
button.innerText = '复制代码';
button.style.backgroundColor = 'rgba(0, 0, 0, 0.2)';
button.style.color = '#fff';
}, 3000);
});
block.style.cssText = 'position: relative;';
block.insertBefore(button, code);
});
var codeTexts = document.querySelectorAll('.wp-block-code pre');
codeTexts.forEach(function(text) {
text.style.color = '#fff';
});
});
</script>




