精美而实用的网站,关注web编程技术、网站运营、SEO推广,让您轻松愉快的学习

为了避免网站内容被被人复制不加版权信息,特意写了一个完美兼容火狐Firefox和Chrome复制内容自动加版权的JS函数,网上找到的都不兼容,青岛星网就自己写了一个跟大家分享。

JS完美兼容火狐Firefox和Chrome复制内容自动加版权函数

var copyAddRight = function(extHTML) {
    var addExtHTML = function(e) {
        var extContent = document.createElement('div');
        extContent.innerHTML = extHTML;
        if (!e) {
            var text = clipboardData.getData("Text");
            clipboardData.setData('Text', text + extContent.innerText);
        } else if (e.clipboardData) {
            e.preventDefault();
            var selection = window.getSelection();
            e.clipboardData.setData('text/plain', selection + extContent.innerText);
        } else {
            var selection = window.getSelection();
            var body = document.getElementsByTagName('body')[0];
            var range = selection.getRangeAt(0);
            extContent.style.position = 'absolute';
            extContent.style.left = '-99999px';
            extContent.innerHTML = selection + extHTML;
            body.appendChild(extContent);
            selection.selectAllChildren(extContent);
            window.setTimeout(function() {
                body.removeChild(extContent);
                selection.removeAllRanges();
                selection.addRange(range);
                body = selection = null;
            },
            0);
        }
    };
    if (typeof(clipboardData) !== 'undefined') {
        document.body.oncopy = function() {
            setTimeout(addExtHTML, 50);
        };
    } else {
        document.oncopy = addExtHTML;
    }
};

JS自动加版权函数调用方法

copyAddRight("<br /> [转载需保留出处 - 青岛星网] 标题:http://www.qdxw.net");
Tags:js Firefox Chrome