为代码模块添加一个复制按钮
插入一个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>