jQuery按钮复制文本内容
这种方法能保证文本内容被复制到windows剪切板,代码示例是复制url
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>复制文本</title> 6 </head> 7 8 <body> 9 <input type="button" value="按钮" id="d_clip_button" /> 10 <script src="jquery-1.10.2.min.js"></script> 11 <script> 12 $(function(){ 13 $("#d_clip_button").click(function(){ 14 var Url = "https://www.taobao.com/"; 15 copyToClipboard(Url); 16 }); 17 }); 18 19 function copyToClipboard(maintext){ 20 if (window.clipboardData){ 21 window.clipboardData.setData("Text", maintext); 22 }else if (window.netscape){ 23 try{ 24 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 25 }catch(e){ 26 alert("该浏览器不支持一键复制!n请手工复制文本框链接地址~"); 27 } 28 var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard); 29 if (!clip) return; 30 var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable); 31 if (!trans) return; 32 trans.addDataFlavor('text/unicode'); 33 var str = new Object(); 34 var len = new Object(); 35 var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString); 36 var copytext=maintext; 37 str.data=copytext; 38 trans.setTransferData("text/unicode",str,copytext.length*2); 39 var clipid=Components.interfaces.nsIClipboard; 40 if (!clip) return false; 41 clip.setData(trans,null,clipid.kGlobalClipboard); 42 } 43 alert("以下内容已经复制到剪贴板" + maintext); 44 } 45 </script> 46 </body> 47 </html>