fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

js原生实现拷贝到剪贴板

Open artdong opened this issue 5 years ago • 1 comments

js原生实现拷贝到剪贴板

artdong avatar Jan 04 '21 06:01 artdong

function copyText (text) {
      let input = document.createElement('input');
      input.setAttribute('readonly', 'readonly');
      input.setAttribute('value', text);
      document.body.appendChild(input);
      input.select(); // 不能少
      if (!text || !text.length) {
         console.log('复制内容不能为空!');
         return;
      }
      input.setSelectionRange(0, text.length);
      if (document.execCommand('copy')) {
         document.execCommand('copy');
         console.log('复制成功!');
      } else {
         console.log('复制失败!');
      }
      document.body.removeChild(input);
}

artdong avatar Jan 04 '21 06:01 artdong