JS实现剪切板添加网站版权、来源

本文介绍了一种在网页上优化复制粘贴功能的方法,通过JavaScript实现,支持Chrome、Firefox及IE9以上版本。该方法能自动在复制的内容后附上文章来源链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 公司官网有这样需求,写好后,备份以后留用。

只兼容chrome、firefox、IE9+等主流浏览器。

   // https://developer.mozilla.org/en-US/docs/Web/Events/copy
    // https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent/ClipboardEvent
    // https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection
    (function (window, document, undefined) {
        if (!window.getSelection) return;
        //获取选中的HTML
        var getSelectedContents = function () {
            if (window.getSelection) { //chrome、firefox
                var range = window.getSelection().getRangeAt(0);
                var container = document.createElement('div');
                container.appendChild(range.cloneContents());
                return container.innerHTML;
                //return document.getSelection(); //只复制文本
            } else if (document.selection) { //IE
                return document.selection.createRange().htmlText;
                //return document.selection.createRange().text; //只复制文本
            }
        };
        document.querySelector("body").addEventListener("copy", function() {
            var selection = window.getSelection(),
                    url = location.href,
                    elem = document.createElement("div");
            elem.innerHTML = getSelectedContents() + "<br/>" + "本文转自:" + url;
            elem.cssText = "position:absolute;left:-99999px;";
            document.querySelector("body").appendChild(elem);
            selection.selectAllChildren(elem);
            setTimeout(function () {
                elem.remove();
            }, 0);
        });
    })(window, document);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值