“复制到剪贴板”的解决方案

 

  这是js+flash的实现方式,先在http://code.google.com/p/zeroclipboard/downloads/list下载ZeroClipboard相关脚本文件,将ZeroClipboard.js和ZeroClipboard.swf文件添加到Solution中,运行即可,测试过几种主流浏览器通过。

 

<head>
    <title>Peter Test</title>
    <script type="text/javascript" src="ZeroClipboard.js"></script>
    <script type="text/javascript">
        var clip = null;
        //function $(id) { return document.getElementById(id); }
        function init() {
            clip = new ZeroClipboard.Client();
            clip.setHandCursor(true);

            clip.glue('d_clip_button');
        }  

  //function my_Click(client) 
  //{
    //clip.setText($('fe_text').value);
  //}

       $("#d_clip_button").click(function (){
            clip.setText($('fe_text').value);
        });

     </script>
</head>
<body onload="init()">
    <h1>
        Peter Test
    </h1>
    <input type="text" id="fe_text" onchange="clip.setText(this.value)" /><br />
    <input type="button" id="d_clip_button" value="Copy"  /><br />
    <input type="text" id="testarea"  />
</body >

当然,网上还有纯脚本的实现方式,我目前用的也是这种方式,但好像只兼容IEFirefox,代码也一并贴出来吧:

 

function copyToClipboard(txt) {
            if (window.clipboardData) {
                window.clipboardData.clearData();
                window.clipboardData.setData("Text", txt);
            } else if (navigator.userAgent.indexOf("Opera") != -1) {
                window.location = txt;
            } else if (window.netscape) {
                try {
                    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                } catch (e) {
                    alert("被浏览器拒绝!\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");
                }
                var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
                if (!clip)
                    return;
                var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
                if (!trans)
                    return;
                trans.addDataFlavor('text/unicode');
                var str = new Object();
                var len = new Object();
                var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
                var copytext = txt;
                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);
            }


 

posted @ 2010-12-29 09:53  peter cheng  阅读(353)  评论(0编辑  收藏  举报