如何在Javascript中将文本复制到剪贴板?

7

我想知道是否有办法将文本复制到剪贴板。我很清楚这个答案,但它已经过去三年了。自那时以来有什么改变吗?


1
Stackoverflow不是四岁了... :-) - gdoron
但是这个问题是在2008年提出的。 =) - Elliot Bonneville
2
开玩笑的,2012年减去2008年等于4。每个人都知道。:P(开玩笑了,当然你是对的。我来修复一下。) - Elliot Bonneville
2个回答

3
此时最简单的做法是使用基于Flash的解决方案。zeroclipboard 是一个常见的解决方案(这里提供了一个不错的教程 here)。
在过去的几年中,浏览器供应商已经删除了对剪贴板的编程访问。Safari / Chrome在WebKit变更后失去了此功能,而FireFox长时间以来一直阻止它。只有IE仍然允许它,但是它在每个页面最初都会显示一个警告。

0

试一下这个

function myFunc() {
  /* Get the text field */
  let copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select();

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
input {
  display: inline-block;
  padding: .60rem;
  font-size: 1rem;
  color: #495057;
  background-color: #f1f1f1;
  border: 1px solid #ced4da;
  border-radius: .25rem;
}

button {
  display: inline-block;
  font-weight: 400;
  color: #ffffff;
  cursor: pointer;
  text-align: center;
  user-select: none;
  background-color: #007bff;
  border: 1px solid transparent;
  padding: .375rem .75rem;
  font-size: 1rem;
  line-height: 1.5;
  border-radius: .25rem;
  outline: 0;
}
<!-- The text field -->
<input type="text" id="myInput" value="Some Random Text">

<!-- The button used to copy the text -->
<button type="button" onclick="myFunc()">Copy</button>


你能解释一下你的答案吗?在所提及的问题中已经使用了 document.exe('copy')。 - slfan

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