方法一:
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) 取消選取區域
應用場景:
復制指定節點的內容