daily-interview / fe-interview

:smiley: 每日一道经典前端面试题,一起共同成长。
https://blog.csdn.net/u010494753
MIT License
172 stars 22 forks source link

js原生实现拷贝到剪贴板 #67

Open artdong opened 3 years ago

artdong commented 3 years ago

js原生实现拷贝到剪贴板

artdong commented 3 years ago
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);
}