hexo-theme-snippet icon indicating copy to clipboard operation
hexo-theme-snippet copied to clipboard

希望添加复制代码功能

Open Lee981265 opened this issue 6 years ago • 2 comments

Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like A clear and concise description of what you want to happen.

Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

Additional context Add any other context or screenshots about the feature request here.

Lee981265 avatar Jan 17 '19 10:01 Lee981265

建议已收到,谢谢

shenliyang avatar Jan 19 '19 13:01 shenliyang

在head.ejs中添加如下代码 js代码

<script type="text/javascript">
function copyToClip(event) {
    let cb = event.target.parentNode;
    var cls = cb.getElementsByClassName("line");
    var pt = ""
    for (var k = 0; k < cls.length; k++) {
        var cl = (cls[k].textContent || cls[k].innerHTML);
        cl = cl.replace('<span class="css"></span>', "\n")
        cl = cl.replace('<span class="javascript"></span>', "\n")
        pt += cl
        pt += "\n";
    }
    const textarea = document.createElement('textarea');
    textarea.value = pt;
    document.body.appendChild(textarea);
    textarea.select();
    if (document.execCommand('copy')) {
        document.execCommand('copy');
    }
    document.body.removeChild(textarea);
    alert("复制成功");
}

function doAddCopyCode() {
    var codeBlocks = document.getElementsByClassName('code');
    for (var i = 0; i < codeBlocks.length; i++) {
        //创建一个div
        var divCopy = document.createElement("div");
        divCopy.innerHTML = "点击复制"
        //为div创建属性class = "test"
        var divattr = document.createAttribute("class");
        divattr.value = "copy_my_code";

        //把属性class = "test"添加到div
        divCopy.setAttributeNode(divattr);
        codeBlocks[i].appendChild(divCopy)

        var code = codeBlocks[i].getElementsByTagName("pre")[1];

        codeBlocks[i].onclick = (e) => {
            copyToClip(e);

        }
    }
}

window.addEventListener('load', function () {
    doAddCopyCode();
}, false);
</script>

样式添加

<style type="text/css">
    .copy_my_code {
        position: absolute;
        top: 0;
        right: 0;
        border: 1px solid;
        background: #555;
        color: #fff;
        margin: 1px;
        padding: 0px 5px;
        cursor: pointer;
    }
</style>

spygg avatar Apr 25 '22 17:04 spygg