H5移动端复制功能实现

 1     // 点击复制信息
 2     copyTxt (txt) {
 3       var u = navigator.userAgent
 4       var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1
 5       // 要先判断当前是什么系统,否则会报错,无法执行语句
 6       if (isAndroid) {
 7         let _input = document.createElement('input')// 直接构建input
 8         _input.value = txt// 设置内容
 9         document.body.appendChild(_input)// 添加临时实例
10         _input.select()// 选择实例内容
11         document.execCommand('Copy')// 执行复制
12         document.body.removeChild(_input)// 删除临时实例
13         if (document.execCommand('Copy')) {
14           Toast('复制成功')
15         } else {
16           Toast('复制失败,请手动复制')
17         }
18       } else {
19         // 数字没有 .length 不能执行selectText 需要转化成字符串
20         const textString = txt.toString()
21         let input = document.querySelector('#copy-input')
22         if (!input) {
23           input = document.createElement('input')
24           input.id = 'copy-input'
25           input.readOnly = 'readOnly'
26           input.style.position = 'absolute'
27           input.style.left = '-1000px'
28           input.style.zIndex = '-1000'
29           document.body.appendChild(input)
30         }
31 
32         input.value = textString
33         // ios必须先选中文字且不支持 input.select()
34         this.selectText(input, 0, textString.length)
35         console.log(document.execCommand('copy'), 'execCommand')
36         if (document.execCommand('copy')) {
37           document.execCommand('copy')
38           Toast('复制成功')
39         } else {
40           Toast('复制失败,请手动输入')
41         }
42         input.blur()
43         document.body.removeChild(input)
44         // input自带的select()方法在苹果端无法进行选择,所以需要自己去写一个类似的方法
45         // 选择文本。createTextRange(setSelectionRange)是input方法
46       }
47     },
48     selectText (textbox, startIndex, stopIndex) {
49       if (textbox.createTextRange) { // ie
50         const range = textbox.createTextRange()
51         range.collapse(true)
52         range.moveStart('character', startIndex)// 起始光标
53         range.moveEnd('character', stopIndex - startIndex)// 结束光标
54         range.select() // 不兼容苹果
55       } else { // firefox/chrome
56         textbox.setSelectionRange(startIndex, stopIndex)
57         textbox.focus()
58       }
59     }

 

posted @ 2020-03-24 18:31  YoYo/切克闹  阅读(1535)  评论(0编辑  收藏  举报