uniapp 实现文本复制功能

1,212 阅读1分钟

uniapp 实现文本复制功能,兼容H5和APP,亲测有效

// 添加 复制 函数
copyText(val){
        let result
        // #ifndef H5
        uni.setClipboardData({
          data: val,
          success() {
                result = true
          },
          fail() {        
                result = false        
          }
        });
        // #endif

        // #ifdef H5 
          let textarea = document.createElement("textarea")
          textarea.value = val
          textarea.readOnly = "readOnly"
          document.body.appendChild(textarea)
          textarea.select() // 选中文本内容
          textarea.setSelectionRange(0, val.length) 
          result = document.execCommand("copy") 
          textarea.remove()    
        // #endif

        uni.showToast({
                title: '已复制到剪切板',
                duration: 1500
        });

        return result
}