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

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

只兼容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);

 

posted @ 2016-05-11 19:48  赵小磊  阅读(467)  评论(0编辑  收藏  举报
回到头部