<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <input class="inp"/> <div id='copy'>复制</div> </body> </html> <script> var input = document.getElementsByClassName('inp')[0]; document.getElementById('copy').onclick = function(){ input.select(); document.execCommand('copy'); } </script>
select() 方法只对 <input> 和 <textarea> 有效,所以,要获取到点击的值,放到input标签中,再选中复制。