首页 > 解决方案 > 从 JavaScript 复制和粘贴文本

问题描述

我试图弄清楚如何从 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...";
   ...
} 

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

标签: javascript

解决方案


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

这是一个 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/


推荐阅读