copyText.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * v-copyText 复制文本内容
  3. * Copyright (c) 2022 ruoyi
  4. */
  5. export default {
  6. beforeMount(el, { value, arg }) {
  7. if (arg === "callback") {
  8. el.$copyCallback = value;
  9. } else {
  10. el.$copyValue = value;
  11. const handler = () => {
  12. copyTextToClipboard(el.$copyValue);
  13. if (el.$copyCallback) {
  14. el.$copyCallback(el.$copyValue);
  15. }
  16. };
  17. el.addEventListener("click", handler);
  18. el.$destroyCopy = () => el.removeEventListener("click", handler);
  19. }
  20. }
  21. }
  22. function copyTextToClipboard(input, { target = document.body } = {}) {
  23. const element = document.createElement('textarea');
  24. const previouslyFocusedElement = document.activeElement;
  25. element.value = input;
  26. // Prevent keyboard from showing on mobile
  27. element.setAttribute('readonly', '');
  28. element.style.contain = 'strict';
  29. element.style.position = 'absolute';
  30. element.style.left = '-9999px';
  31. element.style.fontSize = '12pt'; // Prevent zooming on iOS
  32. const selection = document.getSelection();
  33. const originalRange = selection.rangeCount > 0 && selection.getRangeAt(0);
  34. target.append(element);
  35. element.select();
  36. // Explicit selection workaround for iOS
  37. element.selectionStart = 0;
  38. element.selectionEnd = input.length;
  39. let isSuccess = false;
  40. try {
  41. isSuccess = document.execCommand('copy');
  42. } catch { }
  43. element.remove();
  44. if (originalRange) {
  45. selection.removeAllRanges();
  46. selection.addRange(originalRange);
  47. }
  48. // Get the focus back on the previously focused element, if any
  49. if (previouslyFocusedElement) {
  50. previouslyFocusedElement.focus();
  51. }
  52. return isSuccess;
  53. }