uni-app implements copying text

In the process of working on the project, in order to improve the user experience, it is necessary to have the function of copying text.
The uni.setClipboardData(OBJECT) copy function officially provided by uni-app is not compatible with the H5 side,
so we have to make a distinction. After testing by myself, it can be used and directly enter the code:

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

Guess you like

Origin blog.csdn.net/qq_17355709/article/details/127669794