javascript - 单击文本时将文本复制到剪贴板的脚本
问题描述
我对以下脚本有疑问:
function copyElementText(id) {
var text = document.getElementById(id).innerText;
var elem = document.createElement("textarea");
document.body.appendChild(elem);
elem.value = text;
elem.select();
document.execCommand("copy");
document.body.removeChild(elem);
console.log('Copy made');
}
<font id="text" onclick="copyElementText(this.id)">Copy this text</font>
当您单击它时,此脚本会将文本复制到剪贴板。
我只能使用一次。我需要在 HTML 文件中多次使用它。如何调整脚本以便我可以多次使用它?
谢谢!
解决方案
- 首先,您的代码在一个文本上运行良好。
- 其次,你应该关心
Id
属性
因此,要解决它,您应该添加另一个具有不同ID
属性的文本,如下所示。
id
属性是用于指定文档的唯一标识符
function copyElementText(id) {
var text = document.getElementById(id).innerText;
var elem = document.createElement("textarea");
document.body.appendChild(elem);
elem.value = text;
elem.select();
document.execCommand("copy");
document.body.removeChild(elem);
console.log(text);
}
<font id="text1" onclick="copyElementText(this.id)">Copy this text</font>
<font id="text2" onclick="copyElementText(this.id)">Copy another text</font>
如果有很多<font>
标签,那么最好使用 aclass
而不是id
像下面这样
function copyElementText(event) {
var text = event.innerText;
var elem = document.createElement("textarea");
document.body.appendChild(elem);
elem.value = text;
elem.select();
document.execCommand("copy");
document.body.removeChild(elem);
console.log(text);
}
<font class="text" onclick="copyElementText(this)">Copy this text</font>
<font class="text" onclick="copyElementText(this)">Copy another text</font>
推荐阅读
- haskell - 函数 rem1 :: Eq a => [a] -> a -> [a],从第一个参数中删除第二个参数中提到的 elem
- flutter - 如何配置传感器(加速度计或陀螺仪)以在用户摇晃或旋转手机时执行某些操作?
- sql-server - 无法使用 SQL Server 代理 Powershell CmdExec 步骤处理 Power BI Premium 模型中的分区
- reactjs - 在 React 中,根据初始获取的结果获取数据
- php - number_format() 宽度为 100%
- python-3.x - Matplotlib xticks 隐藏图形光标信息
- laravel - 如何在 Laravel+Vue 应用中使用本地化
- python - 如何以类似于 Python 和 Pyenv 的方式从 shell 管理多个版本的 R
- android - Xamarin.Android 上是否有任何应用事件?
- postgresql - PostgreSQL (pg_hba.conf / postgresql.conf) 与服务器的连接丢失。尝试重置:失败