使用已有插件
- 插件github:https://github.com/zenorocha/clipboard.js
- 使用方式
- 引入 clipboard.min.js
// 引入js文件 <script src ="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.6/clipboard.min.js"> </script> - 元素設(shè)置(我在react的jsx 文件中)
<Button type="primary" data-clipboard-text="復(fù)制內(nèi)容" className="copy" >復(fù)制短鏈</Button> - js 初始化
const clipboard = new window.ClipboardJS('.copy'); clipboard.on('success', function(e) { alert('復(fù)制成功'); });
使用textarea
// 創(chuàng)建文本域元素
const tempTextarea = document.createElement('textarea');
tempTextarea.value = "復(fù)制內(nèi)容";
document.body.appendChild(tempTextarea);
// 設(shè)置文本域被選中
tempTextarea.select();
// 執(zhí)行選中動(dòng)作
document.execCommand('copy');
復(fù)制當(dāng)前頁面已有內(nèi)容
選中參考:https://www.cnblogs.com/sanqianjin/p/9259033.html
// 獲取要選中的元素,創(chuàng)建選中區(qū)域
const range = document.createRange();
const referenceNode = document.querySelector('.links-wrap');
const selection = window.getSelection();
// 設(shè)置選中
range.selectNodeContents(referenceNode);
selection.removeAllRanges();
selection.addRange(range)
// 執(zhí)行復(fù)制
const result = document.execCommand('copy');
// 取消選中
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();