Home >Web Front-end >H5 Tutorial >How to implement the click-to-copy function in html5 pages (complete code)
The content of this article is about how to implement the click-to-copy function (complete code) in HTML5 pages. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In actual work, sometimes we encounter such a demand. There is a link on the page. There is no need to select the link content. You only need to click the copy button to copy the link content to the clipboard. This can be achieved using the clipboard plug-in. The following is a simple demo.
First, you can install the plug-in through npm install clipboard --save-dev
<!DOCTYPE html> <head> <meta charset="UTF-8"> <title>clipboard示例</title> <script src="lib/clipboard/dist/clipboard.min.js"></script> </head> <body> <h2>从属性里复制</h2> <!--data-clipboard-text属性的值将会被复制--> <p id="btn" class="js-copy" data-clipboard-text="111-从属性复制"> <span>复制到剪切板-111</span> </p> <hr> <h2>从另外一个元素复制内容</h2> <textarea id="bar">222-从另外一个元素复制内容</textarea> <button id="btn2" data-clipboard-target="#bar">复制到剪切板-222</button> <hr> <h2>JS里指定复制的内容 <button id="btn3" data-clipboard-target="#bar">复制到剪切板-333</button></h2> <script> //从属性里复制 var btn = document.getElementById('btn'); var clipboard = new Clipboard(btn);//实例化 clipboard.on('success', function(e) {//复制成功执行的回调,可选 console.log(e); }); clipboard.on('error', function(e) {//复制失败执行的回调,可选 console.log(e); }); //从另外一个元素复制内容 var btn2 = document.getElementById('btn2'); var clipboard2 = new Clipboard(btn2);//实例化 clipboard2.on('success', function(e) {//复制成功执行的回调,可选 console.log(e); }); clipboard2.on('error', function(e) {//复制失败执行的回调,可选 console.log(e); }); //JS里指定复制的内容 var btn3 = document.getElementById('btn3'); var clipboard3 = new Clipboard(btn3, { text: function() { return '333-JS里指定复制的内容'; } }); clipboard3.on('success', function(e) {//复制成功执行的回调,可选 console.log(e); }); clipboard3.on('error', function(e) {//复制失败执行的回调,可选 console.log(e); }); </script> </body> </html>
Rendering:
After clicking the copy button, the success callback function will output a Object, which contains information such as copied content. At this time, you can use the paste shortcut key in other places where you input text to paste the contents of the clipboard to the place you need.
Related recommendations:
HTML5 drag-and-drop copy function implementation
##html5 Page click and left and right sliding page scroll_html/css_WEB-ITnose
The above is the detailed content of How to implement the click-to-copy function in html5 pages (complete code). For more information, please follow other related articles on the PHP Chinese website!