将自己的.innerHTML文本内容复制到剪贴板的HTML按钮

时间:2019-04-27 17:55:21

标签: javascript html button copy

有人知道如何制作使用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>

2 个答案:

答案 0 :(得分:1)

select仅在<input><textarea>元素中的文本上定义。您可以动态创建节点元素,并使用按钮的值设置其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

for (const elem of document.getElementsByClassName("copy")) {
  elem.addEventListener("click", e => 
    navigator.clipboard.writeText(e.target.innerText)
  );
}
<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>

答案 1 :(得分:1)

HTML:

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

JS:

{{1}}