zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    Search Insert Position
    *Set Matrix Zeroes
    Spiral Matrix II
    *Spiral Matrix
    combination的eclipse运行结果
    [?]*Combination(递归调用好难)
    [?]*Subset
    *3Sum Closest
    Why am I getting an Unreachable Statement error in Java?
    windows下,emacs的配置文件在哪儿?
  • 原文地址:https://www.cnblogs.com/huanlei/p/5483340.html
Copyright © 2011-2022 走看看