Javascript实现复制文本的功能

作者:IT技术圈子 浏览量:409   更新于 2023-09-02 16:06 标签:

   Javascript实现复制文本功能,可以通过以下两种方式:一、原生Javascript实现;二、通过第三方插件Clipboard.js实现复制功能

一、原生JS复制

示例代码


<html>
  <head>
    <title>原生Javascript实现复制功能</title>
  </head>
  <body>
    <div style="margin: 0 auto;width: 300px;">
      <input type="text" id="inputId"><button onclick="copy()">复制</button>
    </div>
    <script>
      function copy() {
          /* 获取元素对象 */
          var inputElement = document.getElementById("inputId");
          /* 选择复制内容 */
          inputElement.select();
          /* 复制内容到文本域 */
          navigator.clipboard.writeText(inputElement.value);
          /* 弹出已复制的内容 */
          alert("复制的文本为: " + inputElement.value);
      }
    </script>
  </body>
</html>

二、第三方类库clipboard.js复制

clipboard.js官网:https://clipboardjs.com

clipboard.js Github仓库地址:

https://github.com/zenorocha/clipboard.js

示例代码

<html>
  <head>
    <title>clipboard.js实现复制功能</title>
    <script src="https://cdn.staticfile.org/clipboard.js/2.0.4/clipboard.min.js"></script>

  </head>
  <body>
    <div style="margin: 0 auto;width: 300px;">
      <input type="text" id="inputId"><button id="onCopy">复制</button>
    </div>
    <script>
      new ClipboardJS('#onCopy', {
          text: function(trigger) {
              return document.getElementById("inputId").value;
          }
      }).on('success', function(e) {
        alert("复制成功");
        e.clearSelection();
      }).on('error', function(e) {
          alert('复制失败!');
      });
    </script>
  </body>
</html>