Javascript 给网站 / 博客添加复制代码功能 纯 JS

遍历 pre 标签给每个标签命名 id,然后通过双击事件调用复制方法实现最简单代码复制:

Javascript 给网站 / 博客添加复制代码功能 纯 JS
<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(" 复制成功 ".1000)
    }

    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>


手机扫描二维码访问

    本文标题:《Javascript 给网站 / 博客添加复制代码功能 纯 JS》作者:极四维博客
    原文链接:https://cway.top/post/643.html
    特别注明外均为原创,转载请注明。

    分享到微信

    扫描二维码

    可在微信查看或分享至朋友圈。

    相关文章

    发表评论:

    ◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

    «    2025年5月    »
    1234
    567891011
    12131415161718
    19202122232425
    262728293031

    搜索

    控制面板

    您好,欢迎到访网站!
      查看权限

    最新留言

    文章归档

    • 订阅本站的 RSS 2.0 新闻聚合