常规封装
function fallback (text) {
const area = document.createElement('textarea')
area.value = text
area.contentEditable = true
area.style.position = 'fixed'
document.body.appendChild(area)
area.focus()
area.select()
const res = document.execCommand('copy')
area.remove()
return res
}
export default function (text) {
return navigator.clipboard !== void 0
? navigator.clipboard.writeText(text)
: new Promise((resolve, reject) => {
const res = fallback(text)
if (res) {
resolve(true)
}
else {
reject(res)
}
})
}
改进封装
function fallback (text, el) {
const area = document.createElement('textarea')
area.value = text
area.contentEditable = true
area.style.position = 'fixed'
if(el) {
el.appendChild(area)
} else {
document.body.appendChild(area)
}
area.focus()
area.select()
const res = document.execCommand('copy')
area.remove()
return res
}
export default function (text, el) {
return navigator.clipboard !== void 0
? navigator.clipboard.writeText(text)
: new Promise((resolve, reject) => {
const res = fallback(text, el)
if (res) {
resolve(true)
}
else {
reject(res)
}
})
}