>有谁知道如何制作按钮,用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>
select
仅在<input>
或<textarea>
元素中的文本上定义。您可以动态创建节点元素,并使用按钮的值设置其innerText
:
const copyToClipboard = text => {
const ta = document.createElement("textarea");
ta.textContent = text;
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
};
for (const elem of document.querySelectorAll(".copy")) {
elem.addEventListener("click", e => {
copyToClipboard(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>
存在一个更优雅的选项,并且与Chrome/FF兼容:Clipboard.writeText
。
您需要对框架"clipboard-write"
权限才能执行复制,这在下面的堆栈代码段中可能不起作用。
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>
HTML:
<button id="btn" onclick="myFunction()">Copy text</button>
.JS:
function myFunction() {
var copyText = document.getElementById("btn");
navigator.clipboard.writeText(copyText.textContent)
}