提交 | 用户 | age
|
f3f2f5
|
1 |
import { message } from 'ant-design-vue'; |
IW |
2 |
|
d3600d
|
3 |
// `navigator.clipboard` 可能因浏览器设置或浏览器兼容而造成兼容问题 |
f3f2f5
|
4 |
export function copyText(text: string, prompt: string | null = '已成功复制到剪切板!') { |
d3600d
|
5 |
if (navigator.clipboard) { |
L |
6 |
return navigator.clipboard |
|
7 |
.writeText(text) |
|
8 |
.then(() => { |
|
9 |
prompt && message.success(prompt); |
|
10 |
}) |
|
11 |
.catch((error) => { |
|
12 |
message.error('复制失败!' + error.message); |
|
13 |
return error; |
|
14 |
}); |
|
15 |
} |
|
16 |
if (Reflect.has(document, 'execCommand')) { |
|
17 |
return new Promise<void>((resolve, reject) => { |
|
18 |
try { |
|
19 |
const textArea = document.createElement('textarea'); |
|
20 |
textArea.value = text; |
|
21 |
// 在手机 Safari 浏览器中,点击复制按钮,整个页面会跳动一下 |
|
22 |
textArea.style.width = '0'; |
|
23 |
textArea.style.position = 'fixed'; |
|
24 |
textArea.style.left = '-999px'; |
|
25 |
textArea.style.top = '10px'; |
|
26 |
textArea.setAttribute('readonly', 'readonly'); |
|
27 |
document.body.appendChild(textArea); |
|
28 |
textArea.select(); |
|
29 |
document.execCommand('copy'); |
|
30 |
document.body.removeChild(textArea); |
|
31 |
|
|
32 |
prompt && message.success(prompt); |
|
33 |
resolve(); |
|
34 |
} catch (error) { |
|
35 |
message.error('复制失败!' + error.message); |
|
36 |
reject(error); |
|
37 |
} |
|
38 |
}); |
|
39 |
} |
|
40 |
return Promise.reject(`"navigator.clipboard" 或 "document.execCommand" 中存在API错误, 拷贝失败!`); |
f3f2f5
|
41 |
} |