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

How to copy text to the clipboard in Javascript?

本文关键字:文本 复制 剪贴板 Javascript      更新时间:2023-09-26

我想知道是否有任何方法可以将文本复制到剪贴板。我很清楚这个答案,但它已经三年多了。从那以后有什么变化吗?

目前最简单的方法是使用基于Flash的解决方案。zeroclipboard是一种常见的方法(这里提供了一个很好的演练)。

在过去的几年里,浏览器供应商已经取消了对剪贴板的程序访问。Safari/Chrome在WebKit更改后失去了功能,FireFox长期以来一直阻止它。只有IE仍然允许它,但它最初会在每个页面上显示警报。

试试这个

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>