网站博客代码高亮加入复制功能

方法一

把以下代码直接放在 后台 —— 公共设置 的自定义js里就行了。或将下列代码保存为JS文件,然后在相关页面引用即可,如方法二的操作。

    /** 代码块复制 开始 **/
document.addEventListener('DOMContentLoaded', initCodeCopyButton);
function initCodeCopyButton() {
    function initCSS(callback) {
        const css = `
            .btn-code-copy {
                position: absolute;
                top: .4em;
                right: .4em;
                color: white;
                background-color: rgba(51, 51, 51, 0.6);
                border-radius: .5em;
                padding: .01em .2em;
            }
            .btn-code-copy:hover {
                background-color: rgba(51, 51, 51, 1);
                cursor: pointer;
            }
            `;
        const styleId = btoa('btn-code-copy').replace(/[=+\/]/g, '');
        const head = document.getElementsByTagName('head')[0];
        if (!head.querySelector('#' + styleId)) {
            const style = document.createElement('style');
            style.id = styleId;
            if (style.styleSheet) {
                style.styleSheet.cssText = css;
            } else {
                style.appendChild(document.createTextNode(css));
            }
            head.appendChild(style);
        }
        callback();
    };
    function copyTextContent(source) {
        let result = false;
        const target = document.createElement('textarea');
        target.style.opacity = '0';
        target.textContent = source.textContent;
        document.body.appendChild(target);
        try {
            const range = document.createRange();
            range.selectNode(target);
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(range);
            document.execCommand('copy');
            window.getSelection().removeAllRanges();
            result = true;
        } catch (e) { console.log('copy failed.'); }
        document.body.removeChild(target);
        return result;
    };
    function initButton(pre) {
        const code = pre.querySelector('code');
        if (code) {
            const preParent = pre.parentElement;
            const newPreParent = document.createElement('div');
            newPreParent.style = 'position: relative';
            preParent.insertBefore(newPreParent, pre);
            const copyBtn = document.createElement('div');
            copyBtn.innerHTML = 'copy';
            copyBtn.className = 'btn-code-copy';
            copyBtn.addEventListener('click', () => {
                copyBtn.innerHTML = copyTextContent(code) ? 'success' : 'failure';
                setTimeout(() => copyBtn.innerHTML = 'copy', 250);
            });
            newPreParent.appendChild(copyBtn);
            newPreParent.appendChild(pre);
        }
    };
    const pres = document.querySelectorAll('pre');
    if (pres.length !== 0) {
        initCSS(() => pres.forEach(pre => initButton(pre)));
    }
};
/** 代码块复制 结束 **/

方法二

只有鼠标放到代码块,才会显示复制代码,鼠标从代码块移开,复制代码方框消失。支持一篇文章多个代码块的单独复制。

新建codecopy.js

在主题文件里面新建一个codecopy.js文件。在文件里放入以下代码:

var codeblocks = document.getElementsByTagName("pre")
//循环每个pre代码块,并添加 复制代码

for (var i = 0; i < codeblocks.length; i++) {
    //显示 复制代码 按钮
    currentCode = codeblocks[i]
    currentCode.style = "position: relative;"
    var copy = document.createElement("div")
    copy.style = "position: absolute;right: 4px;\
    top: 4px;background-color: white;padding: 2px 8px;\
    margin: 8px;border-radius: 4px;cursor: pointer;\
    z-index: 9999;\
    box-shadow: 0 2px 4px rgba(0,0,0,0.05), 0 2px 4px rgba(0,0,0,0.05);"
    copy.innerHTML = "复制"
    currentCode.appendChild(copy)
    //让所有 "复制"按钮 全部隐藏
    copy.style.visibility = "hidden"
}


for (var i = 0; i < codeblocks.length; i++) {


    !function (i) {
        //鼠标移到代码块,就显示按钮
        codeblocks[i].onmouseover = function () {
            codeblocks[i].childNodes[1].style.visibility = "visible"
        }

        //执行 复制代码 功能
        function copyArticle(event) {
            const range = document.createRange();

            //范围是 code,不包括刚才创建的div
            range.selectNode(codeblocks[i].childNodes[0]);

            const selection = window.getSelection();
            if (selection.rangeCount > 0) selection.removeAllRanges();
            selection.addRange(range);
            document.execCommand('copy');

            codeblocks[i].childNodes[1].innerHTML = "复制成功"
            setTimeout(function () {
                codeblocks[i].childNodes[1].innerHTML = "复制"
            }, 1000);
            //清除选择区
            if (selection.rangeCount > 0) selection.removeAllRanges(); 0
        }
        codeblocks[i].childNodes[1].addEventListener('click', copyArticle, false);

    }(i);

    !function (i) {
        //鼠标从代码块移开 则不显示复制代码按钮
        codeblocks[i].onmouseout = function () {
            codeblocks[i].childNodes[1].style.visibility = "hidden"
        }
    }(i);
}

引用codecopy.js

打开模板目录下的footer.php文件,在文件末尾的前添加下面一行。

<script src="<?php $this->options->themeUrl(); ?>codecopy.js"></script>

👋 感谢您的观看!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享