首页 > 解决方案 > 如何通过单击按钮将文本复制到剪贴板

问题描述

我正在尝试制作一个将文本复制到剪贴板的按钮,但我遇到了麻烦。它是在复制错误的东西。

本质上,我有一个名为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>

标签: javascripthtmlselectcopy

解决方案


您需要创建一个 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>


推荐阅读