vue一键复制

vue一键复制

    copyToClipboard(textToCopy) {
      // navigator clipboard 需要https等安全上下文
      if (navigator.clipboard && window.isSecureContext) {
        // navigator clipboard 向剪贴板写文本
        return navigator.clipboard.writeText(textToCopy);
      } else {
        // document.execCommand('copy') 向剪贴板写文本
        let input = document.createElement('input')
        input.style.position = 'fixed'
        input.style.top = '-10000px'
        input.style.zIndex = '-999'
        document.body.appendChild(input)
        input.value = textToCopy
        input.focus()
        input.select()
        try {
          let result = document.execCommand('copy')
          document.body.removeChild(input)
          if (!result || result === 'unsuccessful') {
            console.log('复制失败')
          } else {
            console.log('复制成功')
          }
        } catch (e) {
          document.body.removeChild(input)
         console.log('当前浏览器不支持复制功能,请检查更新或更换其他浏览器操作')
        }
      }
    }

posted @ 2024-04-12 10:32  菜鸟辉哥  阅读(9)  评论(0编辑  收藏  举报