使用开源插件clipboard.js,示例代码如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/clipboard.js"></script> <style> #container{ position: relative; width: 100px; } #copybtn{ position: absolute; top:0; left:0; right:0; width:100%; height: 40px; background: white; } #content{ width:90%; height: 30px; } </style> </head> <body> <div id="container"> <textarea id="content">文本</textarea> <button id="copybtn" data-clipboard-action="copy" data-clipboard-target="#content"> 复制</button></div> <script> var clipboard = new Clipboard('#copybtn'); clipboard.on('success', function (e) { alert("yes"); }); clipboard.on('error', function (e) { alert("no"); }); </script> </body> </html>
网友回复