复制文本到剪切板
... 2025-7-10 小于 1 分钟
function CopyToClipboard(text) {
// navigator.clipboard 是最新的API
// document.execCommand API已废弃,不推荐使用
// 所以优先使用 navigator.clipboard API
// navigator.clipboard API在移动端复制时可能会失败
// 失败时使用 document.execCommand API 进行复制
navigator.clipboard.writeText(text).then(null, () => {
let ipt = document.createElement('input')
ipt.setAttribute('value', text)
// 使用 focus() 且 未设置 readonly 的话 移动端会出现调起输入键盘的问题
// ipt.setAttribute('readonly', '')
ipt.style.position = 'absolute'
ipt.style.left = '-100%'
ipt.style.width = '100px'
document.body.appendChild(ipt)
// 可取消 移动端会出现调起输入法的问题 可配合readonly解决
// ipt.focus()
ipt.select()
document.execCommand('copy')
ipt.remove()
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22