簡單的復制功能
var text = '被復制的內容'; if (navigator.clipboard) { // clipboard api 復制 navigator.clipboard.writeText(text); } else { var textarea = document.createElement('textarea'); document.body.appendChild(textarea); // 隱藏此輸入框 textarea.style.position = 'fixed'; textarea.style.clip = 'rect(0 0 0 0)'; textarea.style.top = '10px'; // 賦值 textarea.value = text; // 選中 textarea.select(); // 復制 document.execCommand('copy', true); // 移除輸入框 document.body.removeChild(textarea); }
看了大佬的文章,記錄一下方便以后項目封裝使用,可以根據自己實際項目情況進行處理
原文連接:https://www.zhangxinxu.com/wordpress/2021/10/js-copy-paste-clipboard/
