首页 > 解决方案 > 如何将文本从隐藏的文本区域复制到剪贴板?

问题描述

我有一个像这样的隐藏文本区域,其中设置了一些值:

<textarea style="display: none;" id="element_html"></textarea>

单击按钮时,我尝试使用以下 JS 代码将其内容复制到剪贴板:

$('#element_html').select();
document.execCommand('copy');

它仅在文本区域可见时才有效。如何将隐藏的文本区域内容复制到剪贴板?

标签: javascriptjqueryjquery-plugins

解决方案


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


推荐阅读