前端需要用到拷贝到剪贴板功能,网上大部分都是用隐藏input去实现的办法,新建后丢在那里隐藏,复杂的页面还会占用布局,不是很完美,改造了一下,input用完就会销毁,干净整洁。
更新:
document.execCommand 已标记废弃,增加了新方法实现
使用回调函数接收是否拷贝成功结果
/**
* 写入剪贴板
* document.execCommand 已标记废弃
* 如果浏览器支持navigator.clipboard 就使用新方法
* @param text 拷贝的文本
* @param fn 回调函数
* @returns {boolean}
*/
const writeClipboard = (text, fn) => {
if (text) {
if (navigator.clipboard) {
navigator.clipboard.writeText(text).then(() => {
fn(true)
}, function (err) {
console.error('copy text error: ', err);
});
} else {
let tempInput = document.createElement('input')
tempInput.value = text;
document.body.appendChild(tempInput)
tempInput.select()
document.execCommand('copy')
document.body.removeChild(tempInput)
fn(true)
}
}
}
使用
writeClipboard('复制文本', flag => {
if (flag) console.log('复制成功')
})