js点击复制兼容Firefox

 1 <script type="text/javascript">
 2 function copyCode(id){
 3     var testCode=document.getElementById(id).value;
 4     if(copy2Clipboard(testCode)!=false){
 5         alert("生成的代码已经复制到粘贴板,你可以使用Ctrl+V 贴到需要的地方去了哦!  ");
 6     }
 7 }
 8 copy2Clipboard=function(txt){
 9     if(window.clipboardData){
10         window.clipboardData.clearData();
11         window.clipboardData.setData("Text",txt);
12     }
13     else if(navigator.userAgent.indexOf("Opera")!=-1){
14         window.location=txt;
15     }
16     else if(window.netscape){
17         try{
18             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
19         }
20         catch(e){
21             alert("您的firefox安全限制限制您进行剪贴板操作,请打开’about:config’将signed.applets.codebase_principal_support’设置为true’之后重试,相对路径为firefox根目录/greprefs/all.js");
22             return false;
23         }
24         var clip=Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
25         if(!clip)return;
26         var trans=Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
27         if(!trans)return;
28         trans.addDataFlavor('text/unicode');
29         var str=new Object();
30         var len=new Object();
31         var str=Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
32         var copytext=txt;str.data=copytext;
33         trans.setTransferData("text/unicode",str,copytext.length*2);
34         var clipid=Components.interfaces.nsIClipboard;
35         if(!clip)return false;
36         clip.setData(trans,null,clipid.kGlobalClipboard);
37     }
38 }
39 </script>
40 <div>
41 <a href="#" target="_blank"> [<a href="#" onclick="copyCode('txtTestCode1');return false;">点击复制1</a>]<br>
42 <textarea rows=2 id="txtTestCode1" style="width:500px;font-family: Verdana, Arial;font-size:12px;height:55px;border:1px solid #999999;">复制内容1</textarea>
43 </div>
44 <br><br>
45 <div>
46 <a href="#" target="_blank"> [<a href="#" onclick="copyCode('txtTestCode2');return false;">点击复制2</a>]<br>
47 <textarea rows=2 id="txtTestCode2" style="width:500px;font-family: Verdana, Arial;font-size:12px;height:55px;border:1px solid #999999;">复制内容2</textarea>
48 </div>
49 <br><br>
50 <div>
51 <a href="#" target="_blank"> [<a href="#" onclick="copyCode('txtTestCode3');return false;">点击复制3</a>]<br>
52 <textarea rows=2 id="txtTestCode3" style="width:500px;font-family: Verdana, Arial;font-size:12px;height:55px;border:1px solid #999999;">复制内容3</textarea>
53 </div>
54 <br><br>

 

posted @ 2011-07-29 22:21  simman  阅读(1473)  评论(0编辑  收藏  举报