A-A+

复制到剪切板js代码兼容 IE 与 Firefox

2016年10月17日 前端设计 暂无评论 阅读 6 views 次

复制到剪切板这个效果是我们在很多网站会看到的,如果分享网址或分享内容给网站或像本站一样选择代码,都是可以直接使用复制到剪切板这个功能的,下面我来给大家介绍一款兼容性不错的代码。

下面这个代码是我自己最常用的,代码如下:

  1. <title>JS复制到剪切板</title>  
  2. </head>  
  3. <script>  
  4. function showDivLinkCopy() {  
  5.  var msg=document.getElementById("text").value;  
  6.     window.clipboardData.setData("Text",msg);   
  7. }  
  8. </script>  
  9. <body>  
  10. <input name="" type="text" id="text" value="点击右边的复制"  style=" border:1px solid #ccc; padding:4px; font-size:14px; color:#444; width:200px; line-height:20px;" />  
  11. <a href="javascript:void(0);" onclick="showDivLinkCopy()" style="padding-left:15px; line-height:30px; font-size:16px;">复制</a>  
  12. </body>  
  13. </html>  

但是使用起来在ie下没有任何问题,如果在ff浏览器就没有反应了,后来百度了一个兼容性更好复制到剪切板,js代码,此脚本是传递一个字符串给copyToClipboard,它将被复制的文字被放置到剪贴板,您可以粘贴到其他程序,代码如下:

  1. function copyToClipboard(s)   
  2. {   
  3.     if( window.clipboardData && clipboardData.setData )   
  4.     {   
  5.         clipboardData.setData("Text", s);   
  6.     }   
  7.     else  
  8.     {   
  9.         // You have to sign the code to enable this or allow the action in about:config by changing   
  10.         user_pref("signed.applets.codebase_principal_support"true);   
  11.         netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');   
  12.     
  13.         var clip Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);   
  14.         if (!clip) return//xiariboke.net  
  15.     
  16.         // create a transferable   
  17.         var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);   
  18.         if (!trans) return;   
  19.     
  20.         // specify the data we wish to handle. Plaintext in this case.   
  21.         trans.addDataFlavor('text/unicode');   
  22.     
  23.         // To get the data from the transferable we need two new objects   
  24.         var str = new Object();   
  25.         var len = new Object();   
  26.     
  27.         var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);   
  28.     
  29.         var copytext=meintext;   
  30.     
  31.         str.data=copytext;   
  32.     
  33.         trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);   
  34.     
  35.         var clipid=Components.interfaces.nsIClipboard;   
  36.     
  37.         if (!clip) return false;   
  38.     
  39.         clip.setData(trans,null,clipid.kGlobalClipboard);   
  40.     }   
  41. }  

使用上述示例代码…代码如下:

<textarea id='testText'>#COPYTOCLIPBOARD CODE#</textarea><br>
<button onclick='copyToClipboard(document.getElementById('testText').value);'>

权限:基于Mozilla的浏览器将请求许可,方可让这个用户复制剪贴板中的,目前尚无支持safari的脚本可以实现复制到剪切板.

标签:

给我留言