javascript - 将文本从隐藏输入复制到剪贴板在 jQuery 中不起作用

标签 javascript jquery html css

我有以下代码可以通过单击按钮将文本复制到剪贴板。文本位于段落元素中,因此我将该文本移动到隐藏的输入字段,然后将其复制到剪贴板。 但这仅在我将文本移动到文本字段而不是隐藏字段时才有效。我也尝试 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/

最佳答案

你可以尝试在select之前将input的类型改成text,然后把隐藏的类型带回来。

$("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"/>

关于javascript - 将文本从隐藏输入复制到剪贴板在 jQuery 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53761971/

相关文章:

html - 使用 jQuery 将事件绑定(bind)到动态添加到 DOM 的元素

javascript - 页面加载后,如何根据 jQuery 中的类更改图像源

javascript - 如何将 C# 函数中的字符串添加到元标记(引号内)?

javascript - 如何在js中使用require函数

javascript - 与奥蕾莉亚的传承

javascript - 如何使用 ajax 替代方法使 $.post 请求按顺序运行

javascript - 在选择更改时打开新标签 - 仅适用于 Chrome

php - 使用 htmlpurifier 向标签添加属性

html - 使用 webkit-image-set 时如何为非 WebKit 浏览器显示替代内容?

jquery - 在我的页面中放置一些带有图像的 div 的提示