复制文字或图片

发布时间 2023-06-01 10:56:15作者: 你风致
        //复制文字或图片
     copyTextandImg(sets): Promise<void> { console.log(sets); return new Promise((resolve, reject) => { const imgDiv = document.createElement('div'); imgDiv.id = '__imgDiv'; imgDiv.setAttribute('style', 'z-index: -1;position: fixed;'); let child = ''; if (sets.txts) { if (typeof sets.txts === 'string') { child += `<span>${sets.txts}</span>`; } else { sets.txts.forEach((item) => { child += `<span>${item}</span>`; }); } } if (sets.imgs) { if (typeof sets.imgs === 'string') { // sets.imgs = sets.imgs.indexOf('https') > -1 ? sets.imgs.replace('https', 'http') : sets.imgs; child += `<img src="${sets.imgs}" />`; } else { sets.imgs.forEach((item) => { // item = item.indexOf('https') > -1 ? item.replace('https', 'http') : item; child += `<img src="${item}" />`; }); } } imgDiv.innerHTML = child; document.body.insertBefore(imgDiv, document.body.lastChild); const dom = document.getElementById('__imgDiv'); if (dom) { if (window.getSelection) { //chrome等主流浏览器 const selection = window.getSelection(); const range = document.createRange(); range.selectNodeContents(dom); selection && selection.removeAllRanges(); selection && selection.addRange(range); } else if (document.body['createTextRange']) { //ie const range = (document.body as any).createTextRange(); range.moveToElementText(dom); range.select(); } // (window as any).clipboardData.setData("Text", ""); document.execCommand('copy'); (window as any).getSelection().removeAllRanges(); (imgDiv?.parentNode as any).removeChild(imgDiv); resolve(); } else { reject(); } }); }

使用如下:

      const text = `帅哥你谁?`;
      this.copyTextandImg({
          txts: text,
      }).then(() => {
        console.log('复制成功');
      });