0

我试图弄清楚如何从 JavaScript 复制字符串和粘贴。

此代码示例:

function copyLink() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  document.execCommand("copy");
} 

副本来自myInput value

  <input type="text" value="ttps://site.org/" id="myInput">

但我正在尝试从变量中复制文本,不包括html value

 <button onclick="copyText()">Copy text</button>

这是.js为了允许用户复制/粘贴:

function copyText() {
   var text = "long text...";
   ...
} 

它看起来很简单,但似乎我搜索不正确,因为我找不到方法。

4

3 回答 3

1

作为一种快速修复,您可以将要复制的值粘贴到输入字段(甚至是隐藏字段)中,然后以相同的方式进行复制。

这是一个 Codepen 示例:https ://codepen.io/kshetline/pen/ExKwjjq?editors=1111

function copyText() {
  document.getElementById('hidden').value = new Date().toLocaleString();
  var copyText = document.getElementById('hidden');
  copyText.select();
  document.execCommand('copy');  
}
<input id="hidden" type="text" style="opacity: 0; position: absolute; top: -5em">
<button type="button" onclick="copyText()">Copy</button><br>
<label for="paste">Paste here: <input id="paste" type="text"></label>

但是,有一个更高级的剪贴板操作 API,在本文中进行了描述:https ://web.dev/async-clipboard/

于 2020-09-01T21:30:09.210 回答
1

最好的方法是创建一个 Dummy 元素,复制内容并将其从 dom 中删除。

// Create a dummy input
var dummy = document.createElement("input");

// Inject the content
dummy.value=copyText;

// Add it to the dom
document.body.appendChild(dummy);

// Select it
dummy.select();

// Copy the content
document.execCommand("copy");

// Clean the dom
document.body.removeChild(dummy);
于 2020-09-01T21:34:53.700 回答
0

您可以使用异步剪贴板 API:

async function copy() {
  try {
    await navigator.clipboard.writeText(input.value);
    console.log('Value copied to clipboard');
  } catch (err) {
    console.error('Failed to copy: ', err);
  }
}

有关详细信息,请参阅这篇文章

于 2020-12-16T13:42:35.420 回答