适用低版本浏览器及低IOS系统内置webview的js复制方法(vue)

506 阅读1分钟

企业微信20231201-094957@2x.png

    <span class="button" @click="copy(link)">复制</span>
    
    

    copy(text) {
      // 新的异步 Clipboard API,先尝试使用
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(
          () => {
            this.$toast('复制成功!')
          },
          err => {
            console.error('err: ', err)
            this.fallbackCopyTextToClipboard(text) // 回落到旧方法
          }
        )
      } else {
        // 回落到旧的 document.execCommand 方法
        this.fallbackCopyTextToClipboard(text)
      }
    },
    selectText(textbox, startIndex, stopIndex) {
      if (textbox.createTextRange) {
        // ie
        const range = textbox.createTextRange()
        range.collapse(true)
        range.moveStart('character', startIndex) // 起始光标
        range.moveEnd('character', stopIndex - startIndex) // 结束光标
        range.select() // 不兼容苹果
      } else {
        // firefox/chrome
        textbox.setSelectionRange(startIndex, stopIndex)
        textbox.focus()
      }
    },
    fallbackCopyTextToClipboard(copyTxt) {
      // 创建一个 textarea 元素
      const textArea = document.createElement('textarea')
      textArea.style.position = 'fixed' // 防止页面跳动
      textArea.style.top = '0'
      textArea.style.left = '0'
      textArea.style.opacity = '0' // 不显示这个 textarea
      textArea.setAttribute('readonly', '') // 避免在 iOS 上出现键盘
      textArea.value = copyTxt // 设置其 value 为你想复制的内容

      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select() // 选中文本

      try {
        // 尝试执行复制操作
        if (document.execCommand('copy')) {
          document.execCommand('copy')
          this.$toast('复制成功')
        } else {
          this.selectText(textArea, 0, copyTxt.length)
          if (document.execCommand('copy')) {
            document.execCommand('copy')
            this.$toast('复制成功!')
          } else {
            this.$toast('复制失败!')
          }
        }
      } catch (err) {
        this.$toast('无法复制')
      }

      document.body.removeChild(textArea) // 移除 textarea 元素
    },