Guest User

Untitled

a guest
Sep 24th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. const copyToClipboard = input => {
  2. const el = document.createElement('textarea');
  3.  
  4. el.value = input;
  5.  
  6. // Prevent keyboard from showing on mobile
  7. el.setAttribute('readonly', '');
  8.  
  9. el.style.contain = 'strict';
  10. el.style.position = 'absolute';
  11. el.style.left = '-9999px';
  12. el.style.fontSize = '12pt'; // Prevent zooming on iOS
  13.  
  14. const selection = document.getSelection();
  15. let originalRange = false;
  16. if (selection.rangeCount > 0) {
  17. originalRange = selection.getRangeAt(0);
  18. }
  19.  
  20. document.body.appendChild(el);
  21. el.select();
  22.  
  23. // Explicit selection workaround for iOS
  24. el.selectionStart = 0;
  25. el.selectionEnd = input.length;
  26.  
  27. let success = false;
  28. try {
  29. success = document.execCommand('copy');
  30. } catch (err) {
  31. // eslint-disable-next-line
  32. console.error(err)
  33. }
  34.  
  35. document.body.removeChild(el);
  36.  
  37. if (originalRange) {
  38. selection.removeAllRanges();
  39. selection.addRange(originalRange);
  40. }
  41.  
  42. if (!success) {
  43. setTimeout(() => {
  44. // eslint-disable-next-line
  45. window.prompt('复制失败,请手动复制:', input);
  46. }, 200);
  47. } else {
  48. toast.success('复制成功');
  49. }
  50. };
Add Comment
Please, Sign In to add comment