优化复制按钮功能

This commit is contained in:
jingrow 2025-12-29 23:09:16 +08:00
parent 65768b7a4c
commit caa20dfb76

View File

@ -44,15 +44,50 @@ export default {
};
},
methods: {
copyTextContentToClipboard() {
const clipboard = window.navigator.clipboard;
clipboard.writeText(this.textContent).then(() => {
async copyTextContentToClipboard() {
try {
// 使 Clipboard API
if (navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(this.textContent);
this.showCopySuccess();
} else {
// 使 execCommand
this.fallbackCopyTextToClipboard(this.textContent);
}
} catch (error) {
// Clipboard API
this.fallbackCopyTextToClipboard(this.textContent);
}
},
fallbackCopyTextToClipboard(text) {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
textArea.style.top = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
const successful = document.execCommand('copy');
if (successful) {
this.showCopySuccess();
} else {
toast.error(this.$t('Copy failed, please copy manually'));
}
} catch (err) {
toast.error(this.$t('Copy failed, please copy manually'));
} finally {
document.body.removeChild(textArea);
}
},
showCopySuccess() {
this.copied = true;
setTimeout(() => {
this.copied = false;
}, 4000);
toast.success(this.$t('Copied to clipboard!'));
});
}
}
};