[英]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
private copyToClipboard = async (textToCopy: string) => {
await navigator.clipboard.writeText(textToCopy);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.