【网页插件】几行代码为你网站添加复制代码功能

hik
@Ta 2020-03-13发布,2022-06-17修改 12894点击

几行代码为你网站添加复制代码功能,去掉了JQuery依赖,并在代码右上角添加个复制按钮。

思路很简单,遍历pre标签并命名id,pre标签添加双击事件,将id传给方法,方法根据id获取元素内容执行复制。可作为任意网站插件使用!

最后吐槽下IE浏览器,去掉JQ之后我本想of循环遍历,但是IE不支持。

导入网页插件:代码复制插件(当前用户:2,总安装次数:2)
<script>
    let id = 0;
    window.onload = function () {
        let preItems = document.getElementsByTagName('pre');
        for (let index in preItems) {
            let preItem = preItems[index];
            preItem.setAttribute("ondblclick", 'copycode(' + ++id + ')');
            //由于虎绿林高亮插件pre标签内有个code标签,因此我直接给code设置id做辅助方便复制
            //不用按钮的话可以直接获取pre标签中id索引-1的元素作为复制内容
            //如前贴:https://zzw.pw/thread-289.htm
            preItem.getElementsByTagName('code')[0].setAttribute("id", id);
            //设置复制按钮居右 透明度与背景色可自定义
            preItem.innerHTML = '<div name="copyDiv" onclick="copycode(' + id + ')" '
                + 'style="filter:alpha(Opacity=50);-moz-opacity:0.5;opacity: 0.5;cursor: pointer;vertical-align: middle;float:right;background: #F8F8FF;">复制</div>'
                +  preItem.innerHTML;
        }
    }

    function copycode(i) {
        const range = document.createRange();
        range.selectNode(document.getElementById(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>

https://cway.top

回复列表(8|隐藏机器人聊天)
添加新回复
回复需要登录