javascript - 如何使用 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 中。
解决方案
每次运行 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>
推荐阅读
- android - 使用范围存储保存二进制文件
- c# - Asp.Net Core MVC - 返回编辑后的模型不会更改使用 SelectTagHelper 创建的选择
- ios - React Native(0.63)警报在IOS中自动消失
- c++ - 如何在 linux 终端中同时编译和运行 c++ 代码?
- javascript - 带箭头功能的 setState 不起作用
- agora.io - 使用 Agora Web SDK API 时,我们可以在源头静音远程音频吗?
- java - 我可以从底部栏单击侦听器打开片段吗?
- c# - 为什么异步查询失败
- mysql - 在多个连接中获取最大数据
- angular - 如何在角度 2+ 中获取日志跟踪?