JavaScript + Html5 implement button Copy text to clipboard function (mobile webpage compatibility), javascripthtml5
When I was learning Javascript, I met such a requirement. I tried almost all the methods on the Internet. Write down the summary
Usage:Clipboard
Plug-in: https://github.com/zenorocha/clipboard.js/tree/master
Introduce plug-ins: directory \ clipboard. js-master \ dist \ clipboard. min. js
There are various demos in the directory, which implement fixed text replication, input replication, and so on. You can look for ideas;
Below, we will record the method used:
I. Introduction of plug-ins:
<script src="js/clipboard.min.js" type="text/javascript"></script>
2. Add a label attribute: data-clipboard-text
<div id="btn" data-clipboard-text="1"> <span>Copy</span> </div>
3. Define a script: implement the copy function --- (internal scripts are written, errors are always reported externally, and classes cannot be found. The new user does not know much about the script and will add it later)
<Script> var clipboard = new Clipboard ('btn '); clipboard. on ('success', function (e) {e. clearSelection (); // copied successfully}); clipboard. on ('error', function (e) {// copy Failed}); </script>
Supplement:New Clipboard () ---- the parameter can be set to id class, which is the same as that defined in css.
4. Custom copy content;
new Clipboard('.btn', { target: function(trigger) { return trigger.nextElementSibling; }});
Return the content to be copied through return,
5. Copy the content of each list on the list page
You can define the data-clipboard-text attribute for each item.
div.setAttribute("data-clipboard-text","asdf");
Supplement:Almost all computer browsers are supported. Android is supported on mobile phones. Apple has some problems. You need to set the tag to button.
The above section describes how to copy text to the clipboard using the Javascript + Html5 buttons (compatible with mobile Web pages). I hope this will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!