首页 > Web开发 > 详细

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

时间:2016-05-11 21:39:24      阅读:166      评论:0      收藏:0      [点我收藏+]

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

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

 

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

原文:http://www.cnblogs.com/huanlei/p/5483340.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!