js实现复制功能

72 阅读1分钟

js实现复制功能

// 已废弃的功能,用于兼容ip启动的服务不能复制的情况
export const copyText = (value: string, tips?: string): void => {
  // 回退到传统的 document.execCommand 方法
  const textArea = document.createElement('textarea')
  textArea.value = value
  textArea.style.position = 'fixed' // 避免滚动到底部
  document.body.appendChild(textArea)
  textArea.focus()
  textArea.select()
  try {
    const successful = document.execCommand('copy')
    successful && console.log(tips || '复制成功')
  } catch (err) {
    console.error('Fallback failed to copy text', err)
  } finally {
    textArea.remove()
  }
}

/**
 * 复制内容到剪贴板
 * @param {value} 需要复制的内容
 * @param {tips} 提示文案
 */
export const copyDomText = (value: string, tips?: string): void => {
  if (navigator?.clipboard) {
    navigator.clipboard
      .writeText(value)
      .then(() => {
        console.log(tips || '复制成功')
      })
      .catch(err => {
        copyText(value)
      })
  } else {
    copyText(value)
  }
}