shenliyang / hexo-theme-snippet

Snippet 简洁而不简单,也许是一款你寻找已久的hexo主题
https://snippet.shenliyang.com/
MIT License
1.09k stars 208 forks source link

希望添加复制代码功能 #105

Open Lee981265 opened 5 years ago

Lee981265 commented 5 years ago

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.

shenliyang commented 5 years ago

建议已收到,谢谢

spygg commented 2 years ago

在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>