一鍵復制粘貼功能需要用到一個輕量級的JS插件:clipboard.js。
下載到本地后,將其放入項目中,直接引用即可。具體實現代碼如下:
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>一鍵復制粘貼</title> <style> .transfer { width: 90%; margin: 20px auto; font-size: 18px; } .transfer button { margin-top: -5px; float: right; margin-left: 10px; background-color: rgb(3, 169, 244); width: 30%; height: 25px; font-size: 14px; color: white; border: 0; border-radius: 8%; } </style> </head> <body> <div class="transfer"> 支付寶:<span id="zfb_account">11111111111</span> <button onclick="copy1()" data-clipboard-action="copy" data-clipboard-target="#zfb_account" id="copy_zfb">一鍵復制</button> </div> <div class="transfer"> 微信:<span id="wx_account">2222222</span> <button onclick="copy2()" data-clipboard-action="copy" data-clipboard-target="#wx_account" id="copy_wx">一鍵復制</button> </div> <input type="text" /> </body> <script type="text/javascript" src="../js/clipboard.min.js"></script> <script> function copy1() { var clipboard = new Clipboard('#copy_zfb'); clipboard.on('success', function(e) { e.clearSelection(); //選中需要復制的內容 alert("復制成功!"); }); clipboard.on('error', function(e) { alert("當前瀏覽器不支持此功能,請手動復制。") }); } function copy2() { var clipboard = new Clipboard('#copy_wx'); clipboard.on('success', function(e) { e.clearSelection(); //選中需要復制的內容 alert("復制成功!"); }); clipboard.on('error', function(e) { alert("當前瀏覽器不支持此功能,請手動復制。") }); } </script> </html>
效果圖:
注意:如果你在項目中使用了其他的前端框架或者插件,有可能會與clipboard.js插件產生沖突。解決方法,可以使用<iframe/>標簽,將此部分代碼放在一個新的html文件中,然后在主文件中使用<iframe/>標簽引入。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答