【问题标题】:HTML buttons that copy their own .innerHTML text content to the clipboard将自己的 .innerHTML 文本内容复制到剪贴板的 HTML 按钮
【发布时间】:2019-04-27 17:55:21
【问题描述】:

有谁知道如何使用 JavaScript 制作将自己的文本复制到剪贴板的按钮?

我的代码:

function myFunction() {
  var copyText = document.getElementByClassName("copy");
  
  copyText.select();
  document.execCommand("copy");
}
<button class="copy">Click to copy this text data to clipboard.</button>
<button class="copy">Click to copy this different text data to clipboard.</button>

【问题讨论】:

    标签: javascript html button copy


    【解决方案1】:

    select 仅在 &lt;input&gt;&lt;textarea&gt; 元素中的文本上定义。您可以动态创建节点元素并将其innerText 设置为按钮的值:

    for (const elem of document.querySelectorAll(".copy")) {
      elem.addEventListener("click", e => {
        const ta = document.createElement("textarea");
        ta.innerText = e.target.innerText;
        document.body.appendChild(ta);
        ta.select();
        document.execCommand("copy");
        document.body.removeChild(ta);
      });
    }
    <button class="copy">Click to copy this text data to clipboard.</button>
    <button class="copy">Click to copy this different text data to clipboard.</button>

    存在一个更优雅的选项,并且与 Chrome/FF 兼容:Clipboard.writeText

    您需要框架上的"clipboard-write" 权限才能执行复制,这在下面的堆栈 sn-p 中可能不起作用。

    for (const elem of document.getElementsByClassName("copy")) {
      elem.addEventListener("click", e => 
        navigator.clipboard.writeText(e.target.innerText)
          .catch(err => console.error(err))
      );
    }
    <button class="copy">Click to copy this text data to clipboard.</button>
    <button class="copy">Click to copy this different text data to clipboard.</button>

    【讨论】:

    • 我使用了 Clipboard.writeText 方法,效果非常好!仅在FF btw上测试过。也许内容被复制的警告/消息会使这个解决方案更加有用:-)非常感谢!
    【解决方案2】:

    HTML:

    <button id="btn" onclick="myFunction()">Copy text</button>
    

    JS:

    function myFunction() {
      var copyText = document.getElementById("btn");
      navigator.clipboard.writeText(copyText.textContent)
    }
    

    【讨论】:

    • 如果只有一个按钮,这将是最简单/最好的解决方案,但是当按钮超过 1 个时,此解决方案不幸不起作用:-(
    猜你喜欢
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多