In our daily development work, we often use the paste and copy function. Many times, our projects will also allow you to copy to the clipboard. Below we will introduce to you JavaScript Summary of methods for copying to the clipboard!
1. Click the button to copy the content in the text box
2. Copy the topic address and url address and send them to QQ/MSN Friends
3. Directly copy the url
4. When clicking the text box, copy the content in the text box
5. Copy the content in the text box or hidden field
6. Copy the content in the span tag
7. Browser compatibility copyToClipboard("copy content")
function copyToClipboard(txt) { if (window.clipboardData) { window.clipboardData.clearData(); clipboardData.setData("Text", txt); alert("复制成功!"); } else if (navigator.userAgent.indexOf("Opera") != -1) { window.location = txt; } else if (window.netscape) { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch (e) { alert("被浏览器拒绝!\n请在浏览器地址栏输入'about:config'并回车\n然后将 'signed.applets.codebase_principal_support'设置为'true'"); } var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard); if (!clip) return; var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable); if (!trans) return; trans.addDataFlavor("text/unicode"); var str = new Object(); var len = new Object(); var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString); var copytext = txt; 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); alert("复制成功!"); } }
8. Compatible with copy code of major browsers (combined with ZeroClipboard.js)
Summary:
This article introduces in detail the summary of JavaScript methods for copying to the clipboard. Each method has its differences. Friends can choose the method that suits them according to their own needs. I hope it will be helpful to you!
Related recommendations:
javascript - html5 mobile development, how to copy to the clipboard?
A multi-browser "copy to clipboard" javascript code
JS Copy to clipboard sample code
The above is the detailed content of Summary of methods for copying to the clipboard using JavaScript. For more information, please follow other related articles on the PHP Chinese website!