简体   繁体   English

如何使用 onclick html 按钮复制文本?

[英]How to copy a text, using onclick html button?

I create my own portfolio website, on the navigation bar, there is my email.我创建了自己的投资组合网站,在导航栏上,有我的 email。 I want anybody cliking on this email will copy it to the clipboard.我希望任何点击此 email 的人将其复制到剪贴板。 That's what i tried but it's not working !这就是我尝试过的,但它不起作用!

<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);

Note that there is an ability to "request permission" and test for access to the clipboard via the permissions API in Chrome 66.请注意,可以通过 Chrome 66 中的权限 API 来“请求权限”并测试对剪贴板的访问权限。

var text = "text to be copied"
navigator.clipboard.writeText(text).then(_ => {
  console.log('copied successfully!')
})

Buttons do not have a select method, text boxes do.按钮没有 select 方法,文本框有。
You can use a text input to hold the email address to copy to the clipboard.您可以使用文本输入来保存 email 地址以复制到剪贴板。

 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">

Buttons do not have a select method, textboxes have it.按钮没有 select 方法,文本框有。

Better do with a simple for, in this situation, like this:在这种情况下,最好使用简单的 for,如下所示:

 const scrollPosition = 5007; const errorsHeight = [947, 2498, 3495, 4805, 5755]; let errorIdx = -1; for (let i = 0; i < errorsHeight.length; i++) if((errorIdx === -1 && errorsHeight[i] < scrollPosition) || (errorIdx >= 0 && errorsHeight[i] < scrollPosition && errorsHeight[i] > errorsHeight[errorIdx])) errorIdx = i; console.log(errorIdx) //3

Hope this helps.希望这可以帮助。 ;D ;D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM