javascript - 如何通过单击按钮将文本复制到剪贴板
问题描述
我正在尝试制作一个将文本复制到剪贴板的按钮,但我遇到了麻烦。它是在复制错误的东西。
本质上,我有一个名为my_fav_food
. 然后我有一个名为My Fav Food
. 当我单击此按钮时,它会调用函数copying_function
并将my_fav_food
变量解析为函数。然后该功能会自动将文本复制到剪贴板。
<!DOCTYPE html>
<html>
<body>
<script>
var my_fav_food = "My fav food is pizza"
</script>
<button onclick="copying_function(my_fav_food)">My Fav Food</button>
<script>
function copying_function(string) {
string.select();
document.execCommand("string");
}
</script>
</body>
</html>
解决方案
您需要创建一个 DOM 元素并将字符串设置为它,然后以编程方式进行选择。由于您没有将元素附加到 DOM,因此它将在视图中不可见。
<!DOCTYPE html>
<html>
<body>
<script>
var my_fav_food = "My fav food is pizza";
</script>
<button onclick="copying_function(my_fav_food)">My Fav Food</button>
<script>
function copying_function(string) {
// string.select();
const el = document.createElement('textarea');
el.value = string;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
console.log("The data copied successfully! press `ctrl+v` to see output");
document.body.removeChild(el);
}
</script>
</body>
</html>
推荐阅读
- integer - 如何使用 int fint (double) 将双精度值转换为整数,而不会在 Uppaal 中出现“服务器连接丢失”
- algorithm - 在 O(log n) 时间内到 GetMean 的数据结构
- python - 如何在Python中分割AFTER下划线
- macos - 如何修复 QEMU 上无法启动的设备?
- angular - 没有 zone.js 的 Angular 材质组件
- symfony - 如何从 twig Symfony 5.2 覆盖 form_errors()?
- javascript - 从正则表达式替换中删除最后一个符号
- mysql - prisma PANIC:无法在创建中找出 ID
- php - 单选按钮不通过 ajax 发送值
- android - 将参数从片段传递到视图模型函数