uni-copy.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. export default function uniCopy({content,success,error}) {
  2. console.log(content,"123456")
  3. if(!content) return error('复制的内容不能为空 !')
  4. content = typeof content === 'string' ? content : content.toString() // 复制内容,必须字符串,数字需要转换为字符串
  5. /**
  6. * 小程序端 和 app端的复制逻辑
  7. */
  8. //#ifndef H5
  9. uni.setClipboardData({
  10. data: content,
  11. success: function() {
  12. success("复制成功~")
  13. console.log('success');
  14. },
  15. fail:function(){
  16. success("复制失败~")
  17. }
  18. });
  19. //#endif
  20. /**
  21. * H5端的复制逻辑
  22. */
  23. // #ifdef H5
  24. if (!document.queryCommandSupported('copy')) { //为了兼容有些浏览器 queryCommandSupported 的判断
  25. // 不支持
  26. error('浏览器不支持')
  27. }
  28. let textarea = document.createElement("textarea")
  29. textarea.value = content
  30. textarea.readOnly = "readOnly"
  31. document.body.appendChild(textarea)
  32. textarea.select() // 选择对象
  33. textarea.setSelectionRange(0, content.length) //核心
  34. let result = document.execCommand("copy") // 执行浏览器复制命令
  35. if(result){
  36. success("复制成功~")
  37. }else{
  38. error("复制失败,请检查h5中调用该方法的方式,是不是用户点击的方式调用的,如果不是请改为用户点击的方式触发该方法,因为h5中安全性,不能js直接调用!")
  39. }
  40. textarea.remove()
  41. // #endif
  42. }