WordPress页面中代码段添加复制按钮效果

为什么添加复制按钮效果
默认情况下,如果使用古腾堡编辑器插入代码,代码显示的效果比较单调。跟普通文字展示效果几乎没有区别。如果插入的是一大段代码,访客如果需要复制使用,需要手动选择,不够方便。我们可以通过下面的方法来修改代码显示的样式。
如何给代码段添加复制按钮
将下面这段代码插入WordPress,建议插入到页面Header或Body (header)位置。
<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(200, 200, 200, 0.2); color: #fff; border: 1px solid #fff; border-radius: 5px; cursor: pointer; transition: all 0.2s ease-in-out;';
button.addEventListener('mouseenter', function() {
button.style.backgroundColor = 'rgba(0, 0, 0, 0.1)';
});
button.addEventListener('mouseleave', function() {
button.style.backgroundColor = 'rgba(200, 200, 200, 0.2)';
});
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(200, 200, 200, 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>