下面这个代码是我自己最常用的
代码如下 | 复制代码 |
<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; // 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的脚本可以实现复制到剪切板
时间: 2024-05-19 04:10:02