为你的网站博客添加代码块复制功能

纯JS无需第三方插件,各类网站皆可通用,为你网站添加复制代码功能。思路很简单:
遍历pre标签给每个标签命名id,然后通过双击事件调用复制方法实现最简单代码复制

<script>
    window.onload = function () {
        let preItems = document.getElementsByTagName('pre');
        for (let index in preItems) {
            let preItem = preItems[index];
            preItem.setAttribute("id", index);
            preItem.setAttribute("ondblclick", 'copycode(' + index + ')');
            preItem.setAttribute("title", '双击复制');
        }
    }
 
    function copycode(i) {
        const range = document.createRange();
        range.selectNode(document.getElementsByTagName('pre')[i]);
        const selection = window.getSelection();
        if (selection.rangeCount > 0) selection.removeAllRanges();
        selection.addRange(range);
        document.execCommand('copy');
        Toast("复制成功",1500)
    }
 
    function Toast(msg, duration) {
        duration = isNaN(duration) ? 3000 : duration;
        var m = document.createElement('div');
        m.innerHTML = msg;
        m.style.cssText = "max-width:60%;min-width: 150px;padding:0 14px;height: 40px;color: rgb(255, 255, 255);line-height: 40px;text-align: center;border-radius: 4px;position: fixed;top: 50%;left: 50%;transform: translate(-50%, -50%);z-index: 999999;background: rgba(0, 0, 0,.7);font-size: 16px;";
        document.body.appendChild(m);
        setTimeout(function () {
            var d = 0.5;
            m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
            m.style.opacity = '0';
            setTimeout(function () {
                document.body.removeChild(m)
            }, d * 1000);
        }, duration);
    }
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容