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);
  • 相关阅读:
    无法定位程序输入点 ucrtbase.terminate 于动态链接库 api-ms-win-crt-runtime-|1-1-0.dll 上的解决方案
    .net 使用语音播放文字
    Firebird 数据库使用经验总结
    firebird 中的域
    WPF 中 OpenClipboard 失败问题
    Delphi Format 格式化数字
    画圆弧方法
    java.util.concurrent
    linux下软件安装方法
    基于java的http服务器
  • 原文地址:https://www.cnblogs.com/huanlei/p/5483340.html
Copyright © 2011-2022 走看看