首页 |  我的博客 |  查看该博主内容分类 | 

JavaScript将文本复制到剪切板

思路

  1. 创建textarea元素,设置需要复制的内容;
  2. body加入该dom元素;
  3. 通过元素.select()选择,document.execCmand('copy')进行复制;
  4. body移除该dom元素。

示例

const textareaEle = document.createElement("textarea");
textareaEle.value = '你要复制的内容';
document.body.appendChild(textareaEle);
textareaEle.select();
document.execCommand('copy')
document.body.removeChild(textareaEle);

PS:如果网页是本地,即localhost/127.0.0.1开头,可以直接使用navigator.clipboard.writeText("文本数据")更节省内存

posted @ 2023-05-16 09:22  Z哎呀  阅读(590)  评论(0)    收藏  举报