前端点击按钮复制文本

3,096 阅读1分钟

点击按钮复制文本

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

1:css代码部分

  <style type="text/css">
    .wrapper {
      position: relative;
    }
    #input {
      position: absolute;
      top: 0;
      left: 0;
      opacity: 0;
      z-index: -10;
    }
  </style>

2:html代码部分

 <div class="wrapper">
      <p id="text">我把你当兄弟你却想着复制我?</p>
      <textarea id="input">这是幕后黑手</textarea>
      <button onclick="copyText()">copy</button>
    </div>

3:js代码部分

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