ruoyi-geek-App/src/directive/common/copyText.ts

79 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-07-23 04:04:33 +00:00
// #ifdef APP-VUE || H5
2024-01-25 17:08:01 +00:00
/**
* v-copyText
* Copyright (c) 2022 ruoyi
2024-07-23 04:04:33 +00:00
* v-copyText="要复制的文本内容"
* v-copyText:callback="复制成功后的回调函数"
*
2024-01-25 17:08:01 +00:00
*/
2024-07-23 04:04:33 +00:00
import type { Directive, DirectiveBinding } from "vue";
interface ElType extends HTMLElement {
$copyValue: string;
$copyCallback: Function;
$destroyCopy:Function;
}
const vCopyText:Directive = {
beforeMount(el:ElType , binding:DirectiveBinding) {
if (binding.arg === "callback") {
el.$copyCallback = binding.value;
2024-01-25 17:08:01 +00:00
} else {
2024-07-23 04:04:33 +00:00
el.$copyValue = binding.value;
2024-01-25 17:08:01 +00:00
const handler = () => {
copyTextToClipboard(el.$copyValue);
if (el.$copyCallback) {
el.$copyCallback(el.$copyValue);
}
};
el.addEventListener("click", handler);
el.$destroyCopy = () => el.removeEventListener("click", handler);
}
}
}
2024-07-23 04:04:33 +00:00
export default vCopyText;
2024-01-25 17:08:01 +00:00
2024-07-23 04:04:33 +00:00
function copyTextToClipboard(input:string, { target = document.body } = {}) {
2024-01-25 17:08:01 +00:00
const element = document.createElement('textarea');
2024-07-23 04:04:33 +00:00
const previouslyFocusedElement = document.activeElement as HTMLElement;
2024-01-25 17:08:01 +00:00
element.value = input;
// Prevent keyboard from showing on mobile
element.setAttribute('readonly', '');
element.style.contain = 'strict';
element.style.position = 'absolute';
element.style.left = '-9999px';
element.style.fontSize = '12pt'; // Prevent zooming on iOS
const selection = document.getSelection();
2024-07-23 04:04:33 +00:00
if(!selection)return
2024-01-25 17:08:01 +00:00
const originalRange = selection.rangeCount > 0 && selection.getRangeAt(0);
target.append(element);
element.select();
// Explicit selection workaround for iOS
element.selectionStart = 0;
element.selectionEnd = input.length;
let isSuccess = false;
try {
isSuccess = document.execCommand('copy');
} catch { }
element.remove();
if (originalRange) {
selection.removeAllRanges();
selection.addRange(originalRange);
}
// Get the focus back on the previously focused element, if any
if (previouslyFocusedElement) {
previouslyFocusedElement.focus();
}
return isSuccess;
}
2024-07-23 04:04:33 +00:00
// #endif