javascript - 如何将文本从隐藏的文本区域复制到剪贴板?
问题描述
我有一个像这样的隐藏文本区域,其中设置了一些值:
<textarea style="display: none;" id="element_html"></textarea>
单击按钮时,我尝试使用以下 JS 代码将其内容复制到剪贴板:
$('#element_html').select();
document.execCommand('copy');
它仅在文本区域可见时才有效。如何将隐藏的文本区域内容复制到剪贴板?
解决方案
opacity: .01;
做这项工作。您应该将其与:
height:0;
position:absolute;
z-index: -1;
不要使用pointer-events:none;
,因为它也会停止.select()
工作。
function copyContents() {
$('#element_html').select();
document.execCommand('copy');
}
#element_html {
position: absolute;
opacity: .01;
height: 0;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="element_html">Which textarea?</textarea>
<button onclick="copyContents()">Copy</button>
<input type="text" placeholder="Paste it here...">
推荐阅读
- r - 在 R 中并排创建多组直方图
- boost - 运行测试时找不到 boost_filesystem DLL
- java - 具有列表数据类型的并行 for 循环
- javascript - 等待 foreach 循环以在 javascript 中执行内部异步代码
- c - C语言超市模拟
- javascript - 将某些单词(或字母)输入
- scala - 如何计算scala Dataframe中列的特定值的记录更改
- json - 使用 --stream 将相当大的对象扩展到较小的对象
- python - Python,win32 COM:我有一个类名,但无法创建客户端,“'不支持这样的接口”
- sql-server - sqllocaldb 版本 Windows API 调用“RegGetValueW”返回错误代码:0