为文章添加复制按钮

为代码模块添加一个复制按钮

插入一个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>
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇