js实现一键复制的几种方法

JS实现一键复制可以使用以下方法:

1、使用document.execCommand()方法实现复制:

1
2
3
4
5
6
7
8
function copyTextToClipboard(text) {
  var textarea = document.createElement("textarea");
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  document.body.removeChild(textarea);
}

使用示例:

1
copyTextToClipboard("Hello World");

注意:该方法在一些浏览器中可能不被支持。

2、使用Clipboard API实现复制:

1
2
3
4
5
6
7
function copyTextToClipboard(text) {
  navigator.clipboard.writeText(text).then(function() {
    console.log("Text copied to clipboard");
  }, function(err) {
    console.error("Failed to copy text to clipboard: ", err);
  });
}

使用示例:

1
copyTextToClipboard("Hello World");

注意:该方法需要浏览器支持Clipboard API。

3、使用document.execCommand()和Range对象实现复制:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function copyTextToClipboard(text) {
  var range = document.createRange();
  var selection = window.getSelection();
  var textarea = document.createElement("textarea");
  
  textarea.value = text;
  document.body.appendChild(textarea);
  
  range.selectNodeContents(textarea);
  selection.removeAllRanges();
  selection.addRange(range);
  
  textarea.setSelectionRange(0, textarea.value.length);
  document.execCommand("copy");
  
  document.body.removeChild(textarea);
}

使用示例:

1
copyTextToClipboard("Hello World");
版权声明:
作者:89391311
链接:https://www.csev.cn/share/code/20240903409.html/
来源:测试分享
版权声明:本文欢迎任何形式转载,转载时完整保留本声明信息(包含原文链接、原文出处、原文作者、版权声明)即可。本文后续所有修改都会第一时间在原始地址更新。
THE END
根据我国《计算机软件保护条例》第十七条规定:“为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬。本站资源仅供个人学习交流,请于下载后 24 小时内删除,不允许用于商业用途,否则法律问题自行承担。
分享
二维码
打赏
< <上一篇
下一篇>>
文章目录
关闭
目 录
微信扫一扫关注蓝威网官方公众号

微信扫一扫关注蓝威网官方公众号