Old ant farmer--javascript copy content to clipboard

Source: Internet
Author: User

There is a small need in a recent activity page where users can click or press and hold to copy content to the Clipboard, recording the implementation process and the pits encountered.
Common methods
Check out the almighty Google, now the common method is mainly the following two kinds:

Third party libraries: Clipboard.js
Native method: Document.execcommand ()

Take a look at how these two methods are used.
Clipboard.js
This is Clipboard's official website: clipboardjs.com/, it seems to be so simple.
Reference
Direct reference: <script src= "Dist/clipboard.min.js" ></script>
Package: NPM Install clipboard--save, then import clipboard from ' clipboard ';
Use
Copy from input box
Now there is a <input> tag on the page, we need to copy the content, we can do this:
<input id= "demoinput" value= "Hello World" >
<button class= "btn" data-clipboard-target= "#demoInput" > Point I copy </button>
Import Clipboard from ' Clipboard ';
Const BTNCOPY = new Clipboard (' btn ');
Notice that a Data-clipboard-target attribute is added to the <button> tag whose value is the ID of the <input> that needs to be copied, as the name implies from the entire tag.
Direct copy
Sometimes, we don't want to copy content from <input>, just take a value directly from the variable. If we can do this in Vue:
<button class= "btn":d ata-clipboard-text= "Copyvalue" > Point I copy </button>
Import Clipboard from ' Clipboard ';
Const BTNCOPY = new Clipboard (' btn ');
This.copyvalue = ' Hello World ';
Event
Sometimes we need to do something after the copy, and then we need the support of the callback function.
Add the following code to the processing function:
callback function executed after successful replication
Clipboard.on (' Success ', function (e) {
Console.info (' Action: ', e.action); Action name, for example: action:copy
Console.info (' Text: ', e.text); Content, such as: Text:hello word
Console.info (' Trigger: ', E.trigger); Trigger element: For example: <button class= "btn":d ata-clipboard-text= "Copyvalue" > Point I copy </button>
E.clearselection (); Clear Selection
});

callback function to execute after replication failure
Clipboard.on (' Error ', function (e) {
Console.error (' Action: ', e.action);
Console.error (' Trigger: ', E.trigger);
});
Summary
It is also mentioned in the document that if you use Clipboard in a single page, in order to make life cycle management more elegant, remember to Btn.destroy () destroy it after you have finished using it.
Clipboard is not very simple to use. But is it not elegant to use an extra third-party library for a copy function? Then use the native method to achieve the chant.
Document.execcommand () method
Let's look at how this method is defined on the MDN:

which allows one to run commands to manipulate the contents of the editable region.

This means that you can allow commands to be manipulated to manipulate the contents of an editable region, noting that it is an editable region.
Defined

BOOL = Document.execcommand (Acommandname, Ashowdefaultui, avalueargument)

method returns a Boolean value that indicates whether the operation succeeded.

Acommandname: Indicates the command name, such as copy, Cut, etc. (see Command for more commands);
Ashowdefaultui: Whether to display the user interface, generally false;
Avalueargument: Some commands require additional parameters and are generally not available;

Compatibility
This method in the previous compatibility is not very good, but fortunately now is basically compatible with all major browsers, on the mobile side can also be used.

Use
Copy from input box
Now there is a <input> tag on the page, we want to copy the content, we can do this:
<input id= "demoinput" value= "Hello World" >
<button id= "BTN" > Point I copy </button>
Const BTN = document.queryselector (' #btn ');
Btn.addeventlistener (' click ', () = {
Const INPUT = document.queryselector (' #demoInput ');
Input.select ();
if (Document.execcommand (' copy ')) {
Document.execcommand (' copy ');
Console.log (' replication success ');
}
})
Other places to copy
Sometimes there is no <input> tag on the page, we may need to copy the content from a <div>, or copy the variable directly.
Remember that in the definition of the execcommand () method, it can only manipulate editable regions, meaning that this method is not available except for input fields such as <input>, <textarea>.
We need a curve to salvation.
<button id= "BTN" > Point I copy </button>
Const BTN = document.queryselector (' #btn ');
Btn.addeventlistener (' click ', () = {
Const INPUT = document.createelement (' input ');
Document.body.appendChild (input);
Input.setattribute (' value ', ' heard you want to copy me ');
Input.select ();
if (Document.execcommand (' copy ')) {
Document.execcommand (' copy ');
Console.log (' replication success ');
}
Document.body.removeChild (input);
})
It is a curve to salvation success. When using this method, several pits were encountered.
Encounter the Pit
This method works perfectly when you are debugging under Chrome. Then to the mobile side of the debugging, the pit will come out.
Yes, that's right, that's you, iOS ...

When you click Copy, a white screen jitter appears at the bottom of the screen, and a closer look is to pull up the keyboard and instantly close
Know the jitter is due to what produced is better solved. Since it is to pull up the keyboard, that is to focus on the input domain, that is, as long as the input field is not input is good, add Input.setattribute in the code (' readonly ', ' ReadOnly '); Make this <input> is read-only, it will not pull up the keyboard.

Cannot replicate
The problem is that because input.select () does not have all the content selected under iOS, we need to use a different method to select the content, this method is Input.setselectionrange (0, Input.value.length);.

The complete code is as follows:
Const BTN = document.queryselector (' #btn ');
Btn.addeventlistener (' click ', () = {
Const INPUT = document.createelement (' input ');
Input.setattribute (' readonly ', ' ReadOnly ');
Input.setattribute (' value ', ' Hello World ');
Document.body.appendChild (input);
Input.setselectionrange (0, 9999);
if (Document.execcommand (' copy ')) {
Document.execcommand (' copy ');
Console.log (' replication success ');
}
Document.body.removeChild (input);
})

Old ant farmer--javascript copy content to clipboard

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.