关键代码:
<script> function copyUrl(){ document.getElementsByClassName("copytxt")[0].innerText = "这里输入要复制的内容"; const range = document.createRange(); range.selectNode(document.querySelector(".copytxt")); const selection = window.getSelection(); if(selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range); document.execCommand('Copy'); alert("复制成功"); } </script>
完整代码
<head lang="zh-cn"> <meta charset="UTF-8"> <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0' /> <title></title> <style> body{ padding: 20px; text-align: center; } .copytxt{ opacity: 0;/*不可以用display:none和 visibility: hidden;*/ } </style> </head> <body> <a href="javascript:;" onclick="copyUrl()">点我复制</a> <span class="copytxt">大众点评内容</span> <script> function copyUrl(){ document.getElementsByClassName("copytxt")[0].innerText = "这里输入要复制的内容"; const range = document.createRange(); range.selectNode(document.querySelector(".copytxt")); const selection = window.getSelection(); if(selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range); document.execCommand('Copy'); alert("复制成功"); } </script> </body>
效果如下:
点我复制
大众点评内容
点击“点我复制”按钮后,就会把“这里输入要复制的内容”复制到粘贴板中,即Ctrl+C的效果。