经典复制到剪贴板是否需要输入字段/文本区域字段?

问题描述 投票:0回答:3

我不得不将锚标记中的一段文本复制到剪贴板。正如互联网上所建议的那样 HTML:

          <div class="organizer-link">
         <i class="fa fa-link" id="copylink"></i>
         <a href="#" id="linktocopy">https://ticketnshop.com/events/124</a>
          </div>

JS:

 $("#copylink").click(function () {
         console.log("copy link clicked");
         $('#linktocopy').focus();
         $('#linktocopy').text().select();
         document.execCommand("copy");
        console.log($('#linktocopy').val());

    });

但它没有用。

但后来我用文本字段替换了锚标记,并复制了文本。

此过程是否严格要求textarea / input字段。如果不是我做错了什么?

javascript jquery copy clipboard
3个回答
2
投票

你不能使用select(),因为你没有专注于文本字段(也不是textarea)。

这是一个使用范围选择的工作示例。也许你应该看看clipboard.js

$(document).ready(function() {
  $("#copylink").click(function() {
    var containerid = "linktocopy";
    if (document.selection) {
      var range = document.body.createTextRange();
      range.moveToElementText(document.getElementById(containerid));
      range.select().createTextRange();
      document.execCommand("copy");
    } else if (window.getSelection) {
      var range = document.createRange();
      range.selectNode(document.getElementById(containerid));
      window.getSelection().removeAllRanges(range);
      window.getSelection().addRange(range);
      document.execCommand("copy");
      console.log("text copied");
    }
  });
});
<link href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="organizer-link">
  <i class="fa fa-link" id="copylink"></i>
  <a href="#" id="linktocopy">https://ticketnshop.com/events/124</a>
</div>

2
投票

你使用的select()方法仅限于<input type="text">字段和<textarea>框。

在这里查看更多信息select method jquery


1
投票

function copyToClipboard() {
  let textLink = document.getElementById('text');
  let textRange = document.createRange();

  textRange.selectNode(textLink);
  window.getSelection().removeAllRanges(textRange);
  window.getSelection().addRange(textRange);

  document.execCommand("Copy");

  console.log('text was copied!');
}
<div>
  <button id="copy" onclick="copyToClipboard()">Copy</button>
  <a id="text">Copied text from the tag "A"</a>
  <textarea placeholder="Paste this copied text"></textarea>
</div> 
© www.soinside.com 2019 - 2024. All rights reserved.