在做项目的过程中,为了完善用户体验,尝尝需要做复制文本的功能。
而 uni-app官方提供的uni.setClipboardData(OBJECT)复制功能并不兼容H5端,
所以我们要做个区分,经过本人测试,可以使用,直接上代码:
let text = '所要复制的内容'
// #ifdef H5
let textarea = document.createElement("textarea")
textarea.value = text
textarea.readOnly = "readOnly"
document.body.appendChild(textarea)
textarea.select() // 选中文本内容
textarea.setSelectionRange(0, text.length)
uni.showToast({
//提示
title:'复制成功' ,
icon:'success'
})
document.execCommand("copy")
textarea.remove()
// #endif
// #ifndef H5
uni.setClipboardData({
data:text,//要被复制的内容
success:()=>{
//复制成功的回调函数
uni.showToast({
//提示
title:`复制成功`,
icon:'success'
})
}
},true);
// #endif