方法一:
function copyHandle(content){ let copy = (e)=>{ e.preventDefault() e.clipboardData.setData('text/plain',content) alert('复制成功') document.removeEventListener('copy',copy) } document.addEventListener('copy',copy) document.execCommand("Copy"); }
过程:
1. document.execCommand("Copy") 触发复制监听事件
2. e.clipboardData.setData 将内容添加到剪切板
3. 复制完成后,取消监听事件,否则会触发多次
应用场景:
已知复制的内容,传入内容直接调用函数
方法二:
function copyLink(dom) { let range = document.createRange(); let selection = window.getSelection(); range.selectNode(dom); selection.removeAllRanges(); selection.addRange(range); let bool = document.execCommand("copy", "false", null); if (bool) { alert("复制成功"); } document.execCommand("unselect", "false", null); }
过程:
1. range.selectNode 创建选取内容范围
2. removeAllRanges 清除已选择的内容
3. addRanges 添加选取内容,模拟用户选取
4. document.execCommand("Copy") 触发复制事件
5. document.execCommand("unselect", "false", null) 取消选取区域
应用场景:
复制指定节点的内容