Home >Web Front-end >JS Tutorial >Achieve text copying and cutting without relying on Flash or any JS library. Source code download included_javascript skills
The rendering is as follows:
We place a copy button on the web page, which is mainly used to facilitate users to copy complex text such as links. In the past, we relied on Flash through JS, or even relied on the huge js library of jQuery to copy text to the clipboard. . What I want to introduce to you today is a very modern plug-in that does not require flash and does not rely on any other js libraries. It is called clipboard.js.
View demo Download source code
HTML
First load the local clipboard.js file.
Then add the text field content to be copied or cut and the button in the body.
Here, we use the data-attribute of HTML5 to locate the copy object target. It points to the text field #foo, indicating that the value content in #foo is copied. The aria-label attribute defines the copy after successful copying. Information, used to prompt copy result information.
There is also an attribute data-clipboard-action, which defines whether the current operation is copy or cut. The default is copy. When data-clipboard-action="cut", then clicking the button will cut the text, followed by WORD operates the same. Of course, the cut operation only works on text and textarea.
We also don’t need the content of elements such as input and textarea as copy objects. We can define the content to be copied on the button through the ata-clipboard-text attribute. Click the button to copy to the content corresponding to ata-clipboard-text. .
Javascript
Add the following code to the 3f1c4e4b6b16bbbd69b2ee476dc4f83a before 36cc49f0c466276486e50c850b7e4956, save it, open it for browsing, and click the button to copy.
new Clipboard('.btn');
Of course we can further process it. For example, when the copy is completed, it will be more friendly to prompt the successful copy message. Just execute the following code:
var clipboard = new Clipboard('.btn'); clipboard.on('success', function(e) { var msg = e.trigger.getAttribute('aria-label'); alert(msg); e.clearSelection(); });
The above content is what the editor shared with you to realize text copying and cutting without relying on Flash or any JS library. The source code is attached for download. I hope you like it.