// 提供复制文本的方法
const copyText = (textToCopy) => {
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard
.writeText(textToCopy)
.then(() => {
Message.success('复制成功')
})
.catch(() => {
Message.error('复制失败')
})
} else {
// 创建text area
const textArea = document.createElement('textarea')
textArea.value = textToCopy
// 使text area不在viewport,同时设置不可见
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
return new Promise((resolve, reject) => {
// 执行复制命令并移除文本框
document.execCommand('copy') ? resolve() : reject(new Error('出错了'))
textArea.remove()
}).then(
() => {
Message.success('复制成功')
},
() => {
Message.error('复制失败')
},
)
}
}
【前端】复制文本兼容性函数
最新推荐文章于 2024-07-24 10:40:52 发布