JS實現剪切板添加網站版權、來源

 公司官網有這樣需求,寫好後,備份之後留用。css

只兼容chrome、firefox、IE9+等主流瀏覽器。html

   // 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);
相關文章
相關標籤/搜索