zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    轨迹预测-运动递归函数
    Mandelbrot集合及其渲染
    如何检测一个圆在多个圆内?
    【转】三十分钟掌握STL
    【转】如何理解c和c++的复杂类型声明
    有1,2,3一直到n的无序数组,排序
    归并排序
    希尔排序
    快速排序
    冒泡排序
  • 原文地址:https://www.cnblogs.com/helloyoyo/p/12560720.html
Copyright © 2011-2022 走看看