前端实现复制到剪切板

148 阅读1分钟
function copyToClipboard (text: string) {
  var x = document.createElement('input')
  x.defaultValue = x.value = text
  document.body.appendChild(x)
  x.select()

  document.execCommand('copy')
  // @ts-ignore
  if (document.selection) {
    // @ts-ignore
    document.selection.empty()
  } else if (window.getSelection) {
    // @ts-ignore
    window.getSelection().removeAllRanges()
  }

  document.body.removeChild(x)
}