29 lines
787 B
TypeScript
29 lines
787 B
TypeScript
function legacyCopyText(text: string) {
|
|
const textarea = document.createElement("textarea");
|
|
textarea.value = text;
|
|
textarea.style.position = "fixed"; // 避免滚动跳转
|
|
document.body.appendChild(textarea);
|
|
textarea.select();
|
|
|
|
try {
|
|
const successful = document.execCommand("copy");
|
|
document.body.removeChild(textarea);
|
|
return successful;
|
|
} catch (err) {
|
|
console.error("传统复制失败:", err);
|
|
document.body.removeChild(textarea);
|
|
return false;
|
|
}
|
|
}
|
|
export function copyContent(text: string) {
|
|
// 现代浏览器方案
|
|
if (navigator.clipboard) {
|
|
return navigator.clipboard
|
|
.writeText(text)
|
|
.then(() => true)
|
|
.catch(() => legacyCopyText(text));
|
|
}
|
|
// 传统方案
|
|
return Promise.resolve(legacyCopyText(text));
|
|
}
|