js实现复制功能
export const copyText = (value: string, tips?: string): void => {
const textArea = document.createElement('textarea')
textArea.value = value
textArea.style.position = 'fixed'
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
try {
const successful = document.execCommand('copy')
successful && console.log(tips || '复制成功')
} catch (err) {
console.error('Fallback failed to copy text', err)
} finally {
textArea.remove()
}
}
export const copyDomText = (value: string, tips?: string): void => {
if (navigator?.clipboard) {
navigator.clipboard
.writeText(value)
.then(() => {
console.log(tips || '复制成功')
})
.catch(err => {
copyText(value)
})
} else {
copyText(value)
}
}