发布于 4年前

js 复制到剪切板

/**
 * 复制到剪切板
 * @param {String} text 内容
 */
export function copyToClipboardAsync(text) {
  let textArea = document.createElement('textarea')
  textArea.style.position = 'fixed'
  textArea.style.top = '0'
  textArea.style.left = '0'
  textArea.style.width = '2em'
  textArea.style.height = '2em'
  textArea.style.padding = '0'
  textArea.style.border = 'none'
  textArea.style.outline = 'none'
  textArea.style.boxShadow = 'none'
  textArea.style.background = 'transparent'
  textArea.value = text
  document.body.appendChild(textArea)
  textArea.select()

  return new Promise((res, rej) => {
    try {
      let successful = document.execCommand('copy')
      if (!successful) throw Error('该浏览器不支持js复制到剪贴板')
      res()
    } catch (err) {
      rej(err)
    } finally {
      document.body.removeChild(textArea)
    }
  })
}
©2020 edoou.com   京ICP备16001874号-3