支持Firefox和IE的文本复制Javascript

  1. function copyToClipboard(text){
  2.     if(text==null||text=='undefined')
  3.             return;
  4.                 
  5.             //window.clipboardData.setData("Text",text);
  6.    if (window.clipboardData){
  7.          window.clipboardData.setData("Text", text);
  8.        }
  9.    else if (window.netscape){
  10.        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
  11.        var clip = Components.classes['@mozilla.org/widget/clipboard;1']
  12.                      .createInstance(Components.interfaces.nsIClipboard);
  13.        if (!clip) return;
  14.        var trans = Components.classes['@mozilla.org/widget/transferable;1']
  15.                       .createInstance(Components.interfaces.nsITransferable);
  16.        if (!trans) return;
  17.        trans.addDataFlavor('text/unicode');
  18.        
  19.        var str = new Object();
  20.        var len = new Object();
  21.        
  22.        var str = Components.classes["@mozilla.org/supports-string;1"]
  23.                     .createInstance(Components.interfaces.nsISupportsString);
  24.        
  25.        var copytext=text;
  26.        
  27.        str.data=copytext;
  28.        
  29.        trans.setTransferData("text/unicode",str,copytext.length*2);
  30.        
  31.        var clipid=Components.interfaces.nsIClipboard;
  32.        
  33.        if (!clip) return ;
  34.        
  35.        clip.setData(trans,null,clipid.kGlobalClipboard);
  36.        
  37.        }else{
  38.           window.alert("不支持该浏览器的复制功能,请手动复制");
  39.           return;
  40.        }
  41.         window.alert("已复制成功,请直接粘贴$codeFormat");
  42.     }
posted @ 2008-12-31 16:35  lovingprince  阅读(237)  评论(0编辑  收藏  举报