一键复制指定文本到剪切板_移动端_web端PC

一键复制指定文本到剪切板

思路

  1. 利用 input 选中需要复制的文本
  2. 执行复制操作,主要使用 document.execCommand('copy')
  3. 删除 input

实现细节

  1. 创建input元素,用于放需要复制的文本内容
  2. 设置其样式使其不出现在视口内,以不影响当前页面
  3. 需要判断一下设备的类型,因为部分 API 苹果设备不支持
  4. 执行复制操作后删除创建的 input 元素

完整代码

function handle_copy(textString) {
    
    
    const input = document.createElement('input')
    document.body.append(input)
    input.style.position = 'absolute'
    input.readOnly = 'readOnly'
    input.style.left = '-1000px'
    input.style.zIndex = '-100'
    input.value = textString

    const system = navigator.userAgent// 获取系统信息
    // 苹果
    if (system.match(/(iPhone|iPod|iPad);?/i)) {
    
    
      window.getSelection().removeAllRanges() // 将页面所有的文本区域都从选区中移除
      const copyDOM = input // 要复制文字的节点
      const range = document.createRange()
      // 选中需要复制的节点
      range.selectNode(copyDOM)
      // 执行选中元素
      window.getSelection().addRange(range)
      // 执行 copy 操作
      const successful = document.execCommand('copy')
      try {
    
    
        var msg = successful ? '成功' : '失败'
        this.$message('复制' + msg)
      } catch (err) {
    
    
        console.log(err)
      }
      // 移除选中的元素
      window.getSelection().removeAllRanges()
      return successful
    }
    // 安卓
    // if (system.indexOf('Android') > -1) {
    
    
    if (document.execCommand('copy')) {
    
    
      input.select() // IOS不支持 鸿蒙暂不清楚
      const status = document.execCommand('copy')
      input.blur()
      return status
    }
    // }
    input.parentNode.removeChild(input)
}


以上内容仅为个人学习工作中的总结,如有错误或更好的建议,烦请指出

猜你喜欢

转载自blog.csdn.net/qq_44900902/article/details/120026146