copy.js 997 B

123456789101112131415161718192021222324252627282930
  1. export default function (content){
  2. return new Promise((resolve,reject)=>{
  3. // 判断是否支持 clipboard api 复制
  4. try {
  5. if (navigator.clipboard) {
  6. navigator.clipboard.writeText(content).then(resolve).catch(reject);
  7. } else {
  8. let textarea = document.createElement('textarea');
  9. // 隐藏此输入框
  10. textarea.style.position = 'fixed';
  11. textarea.style.opacity = '0';
  12. textarea.style.top = '20px';
  13. document.body.appendChild(textarea);
  14. // 赋值
  15. textarea.value = content;
  16. // 选中
  17. textarea.select();
  18. // 复制
  19. document.execCommand('copy', true);
  20. // 移除输入框
  21. document.body.removeChild(textarea);
  22. }
  23. resolve('ok');
  24. } catch (error) {
  25. reject(error);
  26. }
  27. })
  28. }