This article mainly introduces the js implementation of the copy function (a collection of multiple methods). Friends who need it can refer to it
1. Click the button to copy the content in the text box
2. Copy the topic address and url address, and send it to your friends on QQ/MSN
3. Copy the url directly
4. When clicking the text box, copy the content in the text box Content
5. Copy the content in the text box or hidden field
6. Copy the content in the span tag
7. The browser is compatible with 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("复制成功!"); } }
js realizes automatic text selection when clicking
The most commonly used and concise one is still this, with less code and reduced page loading speed
function copyToClipboard(txt) { if(window.clipboardData){ window.clipboardData.clearData(); window.clipboardData.setData("Text", txt); alert('复制成功!') }else{ alert('请手动复制!') } }
The above is me I compiled it for everyone, I hope it will be helpful to everyone in the future.
Related articles:
How to modify the a tag style in vue?
How to manage header tags using vue-meta
Some common problems with Nuxt.js (detailed tutorial)
React Native related cross-domain resource error issues
Install the latest version of npm in nodejs (detailed tutorial)
The above is the detailed content of How to implement copy function using js code. For more information, please follow other related articles on the PHP Chinese website!