【JS】实现拷贝复制文字

36 阅读1分钟

JS实现拷贝复制文字,把文字复制到剪贴板的功能,提供了2中方案进行兼容,经测试pc端和移动端都没有问题可放心使用

const copyText = async (val) => {
  if (navigator.clipboard && navigator.permissions) {
    await navigator.clipboard.writeText(val)
  } else {
    const textArea = document.createElement('textArea')
    textArea.value = val
    textArea.style.width = 0
    textArea.style.position = 'fixed'
    textArea.style.left = '-999px'
    textArea.style.top = '10px'
    textArea.setAttribute('readonly', 'readonly')
    document.body.appendChild(textArea)

    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
  }
}

copyText("123")