首页 > 解决方案 > 如何使用 JS 复制文本并粘贴到文本区域?

问题描述

我正在寻找如何复制文本然后在 textarea 中自动粘贴新文本的解决方案。我找到了解决方案,但基于 jquery 我正在寻找一些简单的干净 js 。

function copyToClipboard(elementId) {

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

  // Assign it the value of the specified element
  aux.setAttribute("value", document.getElementById(elementId).innerHTML);

  // Append it to the body
  document.body.appendChild(aux);

  // Highlight its content
  aux.select();

  // Copy the highlighted text
  document.execCommand("copy");

  // Remove it from the body
  document.body.removeChild(aux);
  
let textarea = document.getElementById("select-this");
  textarea.focus();
}
<div class="wrapper">
  <p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<p id="p3">P3: I am a 3 paragraph</p>
<button onclick="copyToClipboard('p1')">Copy P1</button>
<button onclick="copyToClipboard('p2')">Copy P2</button>
<button onclick="copyToClipboard('p3')">Copy P3</button>
<br/><br/>
  
  <textarea id="select-this" value="I just copied this with only JavaScript"/></textarea>
</div>

我找到了一些解决方案,但我仍然不知道如何让文本在按下按钮后自动出现在 textarea 中。

标签: javascripthtml

解决方案


每次运行 copyToClipboard 时将复制的值附加到 textarea 的值

function copyToClipboard(elementId) {

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

  // Assign it the value of the specified element
  aux.setAttribute("value", document.getElementById(elementId).innerHTML);

  // Append it to the body
  document.body.appendChild(aux);

  // Highlight its content
  aux.select();

  // Copy the highlighted text
  document.execCommand("copy");

  // Remove it from the body
  document.body.removeChild(aux);

  let textarea = document.getElementById("select-this");
  textarea.focus();
  textarea.value += document.getElementById(elementId).innerHTML
}
<div class="wrapper">
  <p id="p1">P1: I am paragraph 1</p>
  <p id="p2">P2: I am a second paragraph</p>
  <p id="p3">P3: I am a 3 paragraph</p>
  <button onclick="copyToClipboard('p1')">Copy P1</button>
  <button onclick="copyToClipboard('p2')">Copy P2</button>
  <button onclick="copyToClipboard('p3')">Copy P3</button>
  <br/><br/>

  <textarea id="select-this" value="I just copied this with only JavaScript"/></textarea>
</div>


推荐阅读