关于javascript:PC移动端复制文字到粘贴板

4次阅读

共计 752 个字符,预计需要花费 2 分钟才能阅读完成。

function copyText(data){let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android 终端
  let isiOS = !!u.match(/\(i[^;]+;(U;)? CPU.+Mac OS X/); //ios 终端

  let textarea = document.createElement('textarea');
  textarea.id = "copyTextarea";
  textarea.style.width = 0;
  textarea.style.height = 0;
  document.body.appendChild(textarea);
  textarea = document.getElementById('copyTextarea');
  textarea.innerHTML = data;

  if(isiOS == "ios"){const range = document.createRange();
      range.selectNode(document.getElementById('copyTextarea'));
      const selection = window.getSelection();
      if (selection.rangeCount > 0) selection.removeAllRanges();
      selection.addRange(range);
  }else{textarea.select(); // 选中文本 (select() 办法对 IOS 局部版本有效)
  }

  document.execCommand('copy');
  textarea.blur()
  document.body.removeChild(textarea);
  alert('复制胜利!')
},
正文完
 0