jQuery中从隐藏输入框复制文本到剪贴板无法正常工作

4
我有以下代码,可以通过单击按钮将文本复制到剪贴板。文本在段落元素中,所以我将该文本移动到一个隐藏的输入字段,然后将其复制到剪贴板。但是,如果我将文本移动到隐藏字段而非文本字段,则仅适用于前者的情况。我还尝试将输入字段设置为display:none,但结果相同。(我不能将其设置为visibility:hidden,因为空间很重要)。如何解决这个问题?

$("button").on("click", function() {
  var n = $("p").text();
  n = $.trim(n);
  $(".copied").attr("value", n).select();
  document.execCommand("copy");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
This is the copied text!
</p>
<input type="hidden" class="copied"/>
<button>
COPY
</button>
<input type="text" placeholder="paste copied text here"/>

这里是可编辑的jsfiddle:

http://jsfiddle.net/d9a4x6vc/


2
它应该与 opacity: 0; position: absolute; z-index: -1 一起工作。 - user5734311
1
你可能还想添加 pointer-events: none。或者使用 position: fixed; top: -100px 或其他方式,将其完全移出屏幕。 - user5734311
3个回答

3
您可以尝试在选择之前将输入类型更改为文本,然后再将隐藏的类型带回去。

$("button").on("click", function() {
  var n = $("#copyMe").text();
  $(".copied").attr("value", n);
  $(".copied").attr("type", "text").select();
  document.execCommand("copy")
  $(".copied").attr("type", "hidden")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="copyMe">
This is the copied text!
</p>
<input type="hidden" class="copied"/>
<button>
COPY
</button>
<input type="text" placeholder="paste copied text here"/>


1
我最近也遇到了完全相同的问题。我的解决方法是将输入框的位置设置为绝对定位并将其移出屏幕。此外,请注意,即使输入字段的宽度也会影响结果。我试图将宽度和高度设置为0,但复制后仍然没有成功。

1
使用@Chris G在评论中提到的解决方案已经解决了问题。opacity: 0; position: absolute; z-index: -1 - David Johns

1

正如DavidDomain在回答类似问题时所解释的那样,您需要更改输入属性以获取该值。

在您的情况下,您可以尝试这样做:

$("button").on("click", function() {
  var n = $("p").text();
  n = $.trim(n);
  $(".copied").css({
    position: "absolute",
    left: "-1000px",
    top: "-1000px"
  }).attr("value", n).attr("type","text").select();
  $(".copied").attr('css','').attr("type","hidden");
  document.execCommand("copy");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
This is the copied text!
</p>
<input type="hidden" class="copied"/>
<button>
COPY
</button>
<input type="text" placeholder="paste copied text here"/>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接