【问题标题】:How to copy a text, using onclick html button?如何使用onclick html按钮复制文本?
【发布时间】:2022-01-06 17:12:10
【问题描述】:
我创建了自己的投资组合网站,在导航栏上,有我的电子邮件。
我希望任何点击此电子邮件的人都会将其复制到剪贴板。
这就是我尝试过的,但它不起作用!
<button onclick="copy()" id="copy">Copy</button>
function copy() {
var copyText = document.querySelector("#copy");
copyText.select(); document.execCommand("copy");}
document.querySelector("#copy").addEventListener("click", copy);
【问题讨论】:
标签:
javascript
button
onclick
copy
【解决方案1】:
请注意,通过 Chrome 66 中的权限 API,可以“请求权限”并测试对剪贴板的访问权限。
var text = "text to be copied"
navigator.clipboard.writeText(text).then(_ => {
console.log('copied successfully!')
})
【解决方案2】:
按钮没有选择方法,文本框有。
您可以使用文本输入来保存要复制到剪贴板的电子邮件地址。
function copy() {
var copyText = document.querySelector("#email");
copyText.select(); document.execCommand("copy");
}
document.querySelector("#copy").addEventListener("click", copy);
input {margin:-100%}
<button onclick="copy()" id="copy">Copy</button>
<input id=email value="email@so.com">
按钮没有选择方法,文本框有。