• 0
  • 0

选中文档内容复制

2019-07-04 1340 0 admin 所属分类:Javascript

效果如图

  

JS代码

copytext = '';
//页面载入时运行
window.onload = function() {
    initCopy();
}

function initCopy() {
    function selectText() {
        if (document.selection) { //IE浏览器下
            return document.selection.createRange().text; //返回选中的文字
        } else { //非IE浏览器下
            return window.getSelection().toString(); //返回选中的文字
        }
    }
    var oP = document.getElementById('body');
    var oDiv = document.getElementById('copy');
    oP.onmouseup = function(ev) { //设定一个onmouseup事件
        var ev = ev || window.event;
        var left = ev.clientX;
        var top = ev.clientY;
        //其他浏览器
        if (ev.path != undefined && ev.path[0].id != undefined && ev.path[0].id == 'copy') {
            return false;
        }
        //兼容IE
        if (ev.target.id == 'copy') {
            return false;
        }
        copytext = selectText();
        if (copytext.length > 3) {
            setTimeout(function() { //设定一个定时器
                oDiv.style.display = 'block';
                oDiv.style.left = left + 'px';
                oDiv.style.top = top + 'px';
            }, 100);
        } else {
            oDiv.style.display = 'none';
        }
    };
    oP.onclick = function(ev) {
        var ev = ev || window.event;
        ev.cancelBubble = true;
    };
    document.onclick = function() {
        oDiv.style.display = 'none';
    };
    oDiv.onclick = function() {
        oDiv.style.display = 'none';
        var flag = onCopy(copytext);
        setTimeout(function() {
            if (flag) {
                alert("复制成功")
            }
        }, 100);
    };
};


HTML 

https://segmentfault.com/a/1190000004566001

这篇文章讲的是如何对某个标记里面的内容做监听。我把它改造了下监听整个body

首先 我们给body设一个ID

<body id="body">里面填充你的文本内容</body>

添加多一个div复制按钮在body内容

<div id="copy">复制</div>


CSS样式

#copy {
     position: absolute;
     display: none;
     background-color: #1d1b1b;
     padding: 6px 10px;
     color: #fff;
     cursor:pointer;
 }

在IE下也能执行


复制文本函数

function onCopy(text) {
    if (text == null) {
        alert('请选择需要复制的内容');
    }
    if (window.clipboardData) {
        //ie浏览器
        window.clipboardData.setData("text", text)
        return true;
    } else if (window.netscape) {
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        } catch (e) {
            alert("被浏览器拒绝!");
            return false;
        } //\n请在浏览器地址栏输入'about:config'并回车\n然后将 'signed.applets.codebase_principal_support'设置为'true'
        // maak een interface naar het clipboard
        var clip = Components.classes['@mozilla.org/widget/clipboard;1'].
        createInstance(Components.interfaces.nsIClipboard);
        if (!clip) return false;
        //alert("mozilla");
        // maak een transferable
        var trans = Components.classes['@mozilla.org/widget/transferable;1'].
        createInstance(Components.interfaces.nsITransferable);
        if (!trans) return false;
        // specificeer wat voor soort data we op willen halen; text in dit geval
        trans.addDataFlavor('text/unicode');
        // om de data uit de transferable te halen hebben we 2 nieuwe objecten
        // nodig om het in op te slaan
        var str = new Object();
        var len = new Object();
        var str = Components.classes["@mozilla.org/supports-string;1"].
        createInstance(Components.interfaces.nsISupportsString);
        var copytext = text;
        str.data = copytext;
        trans.setTransferData("text/unicode", str, copytext.length * 2);
        var clipid = Components.interfaces.nsIClipboard;
        if (!clip) return false;
        clip.setData(trans, null, clipid.kGlobalClipboard);
        return true;
    } else {
        //不兼容苹果浏览器 得用额外插件
        var element = document.createElement('textarea');
        element.style.position = 'fixed';
        element.style.top = '-500px';
        element.style.left = '-500px';
        //把需要复制的内容放置在该元素中
        element.innerHTML = text;
        document.body.appendChild(element);
        element.select(); // 选择对象
        document.execCommand("Copy"); // 执行浏览器复制命令
        // alert("已复制好,可贴粘。");
        document.body.removeChild(element);
        return true;
    }
}



返回顶部