如何复制按钮文本?

How to copy a button text?

我想在单击按钮时复制按钮中的文本。我重用了 w3 schools 中的代码。与 w3 学校代码的不同之处在于,当您单击一个按钮时,它会从输入中复制文本,我想从我单击的按钮中复制文本。

function copyClipboard() {
  var copyText = document.getElementById("myButton").innerHTML;
  document.execCommand("copy");
}
<button id="myButton" onclick="copyClipboard()">Text I want to copy</button>

当我 console.log copyText 时,它会显示按钮中的文本,但我的文本永远不会被复制。

你知道为什么吗?

您的问题是您只存储了 buttonvalue,但您什么都没有 select,因此不会将任何内容复制到剪贴板。

您需要使用 .select() 将该内容放入 input 和 select 其值 中,以便可以复制:

function copyClipboard() {
  var copyText = document.getElementById("myButton").innerHTML;
  
  var input = document.createElement("input");
  input.value = copyText;
  document.body.appendChild(input);
  input.select();
  document.execCommand("copy");
  document.body.removeChild(input); 
}
<button id="myButton" onclick="copyClipboard()">Text I want to copy</button>

function copyClipboard() {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val(document.getElementById("myButton").innerHTML).select();
    document.execCommand("copy");
    $temp.remove();
}
<button id="myButton" onclick="copyClipboard()">Text I want to copy</button>