原生JS实现复制功能(document.execCommand 和 navigator.clipboard.writeText)
因为document.execCommand('copy')
已弃用
所以我们需使用 异步剪贴板 API [navigator.clipboard.writeText]
代码如下:
function fallbackCopyTextToClipboard(id: string) { const range: any = document.createRange(); range.selectNode(document.getElementById(id)); const selection: any = window.getSelection(); if (selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range); try { const successful = document.execCommand('copy'); //复制选中的文字到剪贴板 selection.removeRange(range); // 移除选中的元素 var msg = successful ? 'successful' : 'unsuccessful'; console.log('Fallback: Copying text command was ' + msg); return msg; } catch (err) { selection.removeRange(range); console.error('Fallback: Oops, unable to copy', err); return false; } } export function copyTextToClipboard(id: string) { if (!navigator.clipboard) { return fallbackCopyTextToClipboard(id); } const range: any = document.createRange(); range.selectNode(document.getElementById(id)); const selection: any = window.getSelection(); if (selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range); return navigator.clipboard.writeText(selection).then(function () { selection.removeRange(range); console.log('Async: Copying to clipboard was successful!'); return 'successful'; }, function (err) { selection.removeRange(range); console.error('Async: Could not copy text: ', err); return false; }); }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步