# JS复制文本
# 安装clipboard插件
npm i clipboard -S
1
import Clipboard from 'clipboard'
export default function copyText(text = '', callback) {
let _resolve
// 复制文本到剪切板
let tempBtn = document.createElement('div')
let clipboard = new Clipboard(tempBtn, {
text: () => { return text }
})
clipboard.on('success', (e) => {
clipboard.destroy()
tempBtn = null
if (callback) {
callback()
} else if (_resolve) {
_resolve()
}
})
if (!callback) {
return new Promise(resolve => {
_resolve = resolve
tempBtn.click()
})
} else {
tempBtn.click()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28