javascript - 从 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...";
...
}
它看起来很简单,但似乎我搜索不正确,因为我找不到方法。
解决方案
作为一种快速修复,您可以将要复制的值粘贴到输入字段(甚至是隐藏字段)中,然后以相同的方式进行复制。
这是一个 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/
推荐阅读
- python-3.x - 演讲者语音的 Python Speech-to-Text 翻译
- dataweave - Mule 4 : 属性文件 : 对于对 Mule 4 应用程序的每个请求,是否建议重复从属性文件中读取项目?
- javascript - 道具未捕获类型错误:无法读取未定义的属性“名称”
- google-cloud-platform - Cloud SQL 代理 - 消息:权限不足
- android - 从 Android 模拟器连接到本地 asp.net Web 服务器
- pytorch - 使用不同长度的批次进行 PyTorch 训练?
- c++ - 如何在 C++ 中存储一组整数值
- perforce - Perforce&Swarm:提交更改后文件从工作区中删除
- arduino - 如何使用 Google Drive REST API v3 执行分段上传
- javascript - 从 node.js 应用程序到达 gmail 时,长链接被破坏