A-A+
复制到剪切板js代码兼容 IE 与 Firefox
复制到剪切板这个效果是我们在很多网站会看到的,如果分享网址或分享内容给网站或像本站一样选择代码,都是可以直接使用复制到剪切板这个功能的,下面我来给大家介绍一款兼容性不错的代码。
下面这个代码是我自己最常用的,代码如下:
- <title>JS复制到剪切板</title>
- </head>
- <script>
- function showDivLinkCopy() {
- var msg=document.getElementById("text").value;
- window.clipboardData.setData("Text",msg);
- }
- </script>
- <body>
- <input name="" type="text" id="text" value="点击右边的复制" style=" border:1px solid #ccc; padding:4px; font-size:14px; color:#444; width:200px; line-height:20px;" />
- <a href="javascript:void(0);" onclick="showDivLinkCopy()" style="padding-left:15px; line-height:30px; font-size:16px;">复制</a>
- </body>
- </html>
但是使用起来在ie下没有任何问题,如果在ff浏览器就没有反应了,后来百度了一个兼容性更好复制到剪切板,js代码,此脚本是传递一个字符串给copyToClipboard,它将被复制的文字被放置到剪贴板,您可以粘贴到其他程序,代码如下:
- function copyToClipboard(s)
- {
- if( window.clipboardData && clipboardData.setData )
- {
- clipboardData.setData("Text", s);
- }
- else
- {
- // You have to sign the code to enable this or allow the action in about:config by changing
- user_pref("signed.applets.codebase_principal_support", true);
- netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
- var clip Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
- if (!clip) return; //xiariboke.net
- // create a transferable
- var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
- if (!trans) return;
- // specify the data we wish to handle. Plaintext in this case.
- trans.addDataFlavor('text/unicode');
- // To get the data from the transferable we need two new objects
- var str = new Object();
- var len = new Object();
- var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);
- var copytext=meintext;
- 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);
- }
- }
使用上述示例代码…代码如下:
<textarea id='testText'>#COPYTOCLIPBOARD CODE#</textarea><br>
<button onclick='copyToClipboard(document.getElementById('testText').value);'>
权限:基于Mozilla的浏览器将请求许可,方可让这个用户复制剪贴板中的,目前尚无支持safari的脚本可以实现复制到剪切板.