Copy the specified text to the clipboard with one click_mobile terminal_web terminal PC

Copy the specified text to the clipboard with one click

train of thought

  1. Use to inputselect the text to be copied
  2. To perform a copy operation, the main usedocument.execCommand('copy')
  3. deleteinput

implementation details

  1. Create an input element to put the text content that needs to be copied
  2. Set its style so that it does not appear in the viewport so as not to affect the current page
  3. Need to judge the type of device, because some APIApple devices do not support
  4. Deletes the created inputelement

full code

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)
}


The above content is only a summary of personal study and work. If there are any mistakes or better suggestions, please point them out.

Guess you like

Origin blog.csdn.net/qq_44900902/article/details/120026146