将字符串复制到剪贴板,而不使用DOM元素? [英] Copy string to clipboard, without using a DOM element?

查看:56
本文介绍了将字符串复制到剪贴板,而不使用DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个有效的代码:

let textarea = document.createElement('textarea');
textarea.setAttribute('type', 'hidden');
textarea.textContent = 'the string you want to copy';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');

如您所见

-我手头有字符串要复制.但是我必须创建一个临时的隐藏DOM元素来对字符串进行评分,然后再将其复制到剪贴板.

as you can see - I have the string to copy in hand. But I have to create a temporary hidden DOM element to score the string before copying to the clipboard.

我的问题是,是否有一些API可以完全不需要DOM复制到剪贴板?像这样的东西:

My question is, is there some API to copy to clipboard without needing the DOM at all? something like this:

document.execCommand('copy', 'the string data to put in clipboard');

似乎很奇怪,DOM是执行此操作所必需的.另外,请注意,这个剪贴板API非常奇怪,其他人都同意吗?

seems weird that the DOM is necessary to do this. Also, as a side note, this clipboard API is super strange, anyone else agree?

推荐答案

我最近遇到了和您一样的问题,但是没有一个解决方案提供了不影响DOM的解决方案.以下内置功能可以为您提供帮助.

I recently faced the same question like you but none of solution provided the solution without affecting DOM. Following built-in function help you.

copyToClipboard("Your variable/string")

copyToClipboard 功能允许您将变量或字符串复制到系统剪贴板.这是剪贴板API 单击文档的一部分.

copyToClipboard function allows you to copy the variable or strings to the system clipboard. This is a part of Clipboard API click for Docs.

这篇关于将字符串复制到剪贴板,而不使用DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆