Example of implementing a one-click copy text using clipboard.js


Recently in the mall project, there is a need to click copy the order number, and then I feel that the original replication method can be used and the third-party library can be used. .


This method is not too good, but also to see if the browser supports, easy to pick up.

/ / can be implemented with Window.clipboardData.SetData (‘Text’, ‘content’) in IE. // CLIPBOARDDATA in IE is the properties of Window, while other browsers are the properties of the corresponding EVENT object, which is actually a security measures to prevent unauthorized access, in order to compatibility with other browsers, so we can’t pass CLIPBoardData is implemented. // Specific practice: // 1. Create a hidden input box // 2. When you click, put the content you want to copy in the input box //3. Select the text content input.select () // 4. Here only Can choose text with input or textarea. // 5. Execute the copy command for the browser Document.execCommand (“Copy”). Function CopyText () {var text = Document.GtelementByid (“text”). InnerText; // Get the content you want to copy can also pass Var INPUT = Document.GetElementByid (“Input”); // Get hidden Input Dom Input .value = text; // Modify the content INPUT.SELECT (); // selection text Document.execCommand (“copy”); // Execute the browser copy command Alert (“copy success”);} // eventYou can modify Document.Body.Oncopy = E => {// monitor global copying is documented by E => {// Listening to the global copy: Document.addeventListener (“copy”, e => {// Listening What to do} in global copy});
 Use clipboard.js   
We must install

NPM Install Clipboard – Save

Introduced in mian.js, of course, we can also use .vue Introduction, because I have been replicated more than one place, so I introduced directly in main.js.

Import clipboard from ‘clipboard’; // Register to Vue prototype Vue.Prototype.clipboard = clipboard;
   


// Dom ···

// Dom ···
// Dom ··· // Dom ···
 // Dom ···  {{OrderData.Ordersn}}  ··· // js ··· COPYLINK () {let _this = this; let clipboard = new this.clipboard (". CobyOrDersn); Clipboard.on ('Success') ({); _this. $ TOAST ("Replication Success")})Clipboard.on ('error', function () {_this. $ toast ("copy failed")};} ··· 


Functional Clipboard.js More simple, we can also use it to cut, you can also copy the value of other elements, etc., the specific use can be viewed: clipboard.js;

 Small knot  
About the browser one-click copy, it is recommended to use clipboard.js, because the native method compatibility is not very good, and the clipboard.js file is not big, but it can Help us do a lot of things, alleviate a lot of debugging and avoiding the pit. The above is just recording the problems you encounter. If there is any mistake, please refer to you, I hope to help everyone, I hope everyone will support Tumi Cloud.
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment