最近的一个需求,领导要求点击按钮实现复制文字,省去用户ctrl+c的步骤。 关键点就是调用 document.execCommand(“copy”); 执行浏览器复制命令。。 有需要的小伙伴自取哦。或者有更好的给我留言哦

1:css代码部分

  1. <style type="text/css">
  2. .wrapper {
  3. position: relative;
  4. }
  5. #input {
  6. position: absolute;
  7. top: 0;
  8. left: 0;
  9. opacity: 0;
  10. z-index: -10;
  11. }
  12. </style>

2:html代码部分

  1. <div class="wrapper">
  2. <p id="text">要复制的文本</p>
  3. <textarea id="input">这是幕后黑手</textarea>
  4. <button onclick="copyText()">copy</button>
  5. </div>

3:js代码部分

  1. <script type="text/javascript">
  2. function copyText() {
  3. var text = document.getElementById("text").innerText;
  4. var input = document.getElementById("input");
  5. input.value = text; // 修改文本框的内容
  6. input.select(); // 选中文本
  7. document.execCommand("copy"); // 执行浏览器复制命令
  8. alert("复制成功");
  9. }
  10. </script>