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