首页 / 问答 / JavaScript或者jQuery如何实现将网页内容一键复制到剪切板的功能?

JavaScript或者jQuery如何实现将网页内容一键复制到剪切板的功能?

CSS HTML javascript Jquery js 3.18K 次浏览
0

假如在HTML网页中,需要复制一个元素(div,p,input或者其他)的文本内容到剪切板,使用Javascript或者jQuery应该如何实现呢?

回复 [×]
提交评论
请输入评论内容

4 个回答

  • 0

    使用document.execCommand("copy")命令可以实现复制网页内容到剪切板的功能,jQuery版本如下:

    function copyToClipboard(element) {
      var $temp = $("<input>");
      $("body").append($temp);
      $temp.val($(element).text()).select();
      document.execCommand("copy");
      $temp.remove();
    }
    

    以下是简单的使用示例:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <p id="p1">P1: I am paragraph 1</p>
    <p id="p2">P2: I am a second paragraph</p>
    <button onclick="copyToClipboard('#p1')">Copy P1</button>
    <button onclick="copyToClipboard('#p2')">Copy P2</button>
    <br/><br/><input type="text" placeholder="Paste here for test" />
    

    以上方法可在以下浏览器中运行:Chrome 43,Internet Explorer 10,Firefox 41,Safari 10

    如果你不想使用jQuery,以下则是纯JavaScript的实现方式:

    function copyToClipboard(elementId) {
      var aux = document.createElement("input");
      aux.setAttribute("value", document.getElementById(elementId).innerHTML);
      document.body.appendChild(aux);
      aux.select();
      document.execCommand("copy");
      document.body.removeChild(aux);
    }
    

    使用示例:

    <p id="p1">P1: I am paragraph 1</p>
    <p id="p2">P2: I am a second paragraph</p>
    <button onclick="copyToClipboard('p1')">Copy P1</button>
    <button onclick="copyToClipboard('p2')">Copy P2</button>
    <br/><br/><input type="text" placeholder="Paste here for test" />
    
    Rector的个人主页

    Rector

    2020-01-16 回答

    • 0

      这里还提供一个比较完整的基于JavaScript复制网页内容的实现方式,如下:

      document.getElementById("copyButton").addEventListener("click", function() {
          copyToClipboardMsg(document.getElementById("copyTarget"), "msg");
      });
      
      document.getElementById("copyButton2").addEventListener("click", function() {
          copyToClipboardMsg(document.getElementById("copyTarget2"), "msg");
      });
      
      document.getElementById("pasteTarget").addEventListener("mousedown", function() {
          this.value = "";
      });
      
      
      function copyToClipboardMsg(elem, msgElem) {
          var succeed = copyToClipboard(elem);
          var msg;
          if (!succeed) {
              msg = "不支持复制或者复制功能已被禁用.请使用Ctrl+C来复制"
          } else {
              msg = "文本已成功复制到剪切板"
          }
          if (typeof msgElem === "string") {
              msgElem = document.getElementById(msgElem);
          }
          msgElem.innerHTML = msg;
          setTimeout(function() {
              msgElem.innerHTML = "";
          }, 2000);
      }
      
      function copyToClipboard(elem) {
          var targetId = "_hiddenCopyText_";
          var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
          var origSelectionStart, origSelectionEnd;
          if (isInput) {
              target = elem;
              origSelectionStart = elem.selectionStart;
              origSelectionEnd = elem.selectionEnd;
          } else {
              target = document.getElementById(targetId);
              if (!target) {
                  var target = document.createElement("textarea");
                  target.style.position = "absolute";
                  target.style.left = "-9999px";
                  target.style.top = "0";
                  target.id = targetId;
                  document.body.appendChild(target);
              }
              target.textContent = elem.textContent;
          }
          var currentFocus = document.activeElement;
          target.focus();
          target.setSelectionRange(0, target.value.length);
      
          var succeed;
          try {
                succeed = document.execCommand("copy");
          } catch(e) {
              succeed = false;
          }
      
          if (currentFocus && typeof currentFocus.focus === "function") {
              currentFocus.focus();
          }
      
          if (isInput) {
              elem.setSelectionRange(origSelectionStart, origSelectionEnd);
          } else {
              target.textContent = "";
          }
          return succeed;
      }
      

      使用示例:

      <input id="copyTarget" value="文本框中的内容"> <button id="copyButton">复制</button><br><br>
      <span id="copyTarget2">非文本框中的内容</span> <button id="copyButton2">复制</button><br><br>
      <input id="pasteTarget">按Ctrl+V将剪切板中的内容粘贴到这里看效果<br><br>
      <span id="msg"></span><br>
      
      Rector的个人主页

      Rector

      2020-01-16 回答

      • 0

        使用第三方剪切板插件clipboard.js,它既可以复制纯文本,也可以复制富文本内容并且不使用Flash。clipboard.js使用起来也非常简单,方便,示例如下:

        <button id='markup-copy'>Copy Button</button>
        
        <script>
            document.getElementById('markup-copy').addEventListener('click', function() {
                clipboard.copy({
                    'text/plain': '纯文本内容',
                    'text/html': '<i>这是</i> 一段 <b>富文本</b>内容'
                }).then(
                    function(){console.log('success'); },
                    function(err){console.log('failure', err);
                });
            });
        </script>
        
        Rector的个人主页

        Rector

        2020-01-16 回答

        • 0

          clipboard.js的完整示例如下:

          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
          <script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>
          
          <p id="content">这里一段示例文本,请点击复制按钮测试。</p>
          
          <a class="copy-text" data-clipboard-target="#content" href="#">复制文本</a>
          
          $(function(){
            new Clipboard('.copy-text');
          });
          
          Rector的个人主页

          Rector

          2020-01-16 回答

          我来回答