简体   繁体   English

如何使用 a<button>和 JS 复制到剪贴板?</button>

[英]How to Copy to Clipboard Using a <button> and JS?

I want to be able to have the user click a button and have javascript copy some certain text into their clipboard.我希望能够让用户单击一个按钮并让 javascript 将某些特定文本复制到他们的剪贴板中。 I was able to get this to work using a, where any value they put in would be copied, but is there any way I can do it with just a and some?我能够使用 a 使其工作,在那里他们输入的任何值都将被复制,但是有什么方法可以只用 a 和一些来完成吗?

I tried the following:我尝试了以下方法:

<html>
<head>
<title>
</title>
</head>
<body>
<button id='myBtn' onclick='myFunction()'>Click Me</button>
</body>
<script>
function myFunction() {
  var copyText = 'CopiedText';
  copyText.select();
  copyText.setSelectionRange(0, 99999)
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>
</html>

you can see w3c document right here.您可以在此处查看w3c 文档 here's the example这是示例

<html>

<head>
    <title>
    </title>
</head>

<body>
    <button id='myBtn' onclick='myFunction()'>Click Me</button>
    <textarea></textarea>
</body>
<script>
    async function myFunction() {
        var copyText = 'CopiedText22';
        var data = [new ClipboardItem({ "text/plain": new Blob([copyText], { type: "text/plain" }) })];
        await navigator.clipboard.write(data);
        alert(`Copied the text: ${copyText} successfully copied`);

    }
</script>

</html>

and then you can paste the result to textarea然后您可以将结果粘贴到 textarea

  1. The execCommand('copy') API isn't supported in Safari and in some version of chrome or mozila. Safari 和某些版本的 chrome 或 mozila 不支持 execCommand('copy') API。
  2. Try to use the command below to copy or write text on clipboard.尝试使用以下命令在剪贴板上复制或写入文本。
  3. call this function on button click.单击按钮时调用此 function。
  4. For more info refer: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard有关更多信息,请参阅: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard

   private copyToClipboard =  async (textToCopy: string) => {
      await navigator.clipboard.writeText(textToCopy);
   };

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

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