js实现复制内容到剪贴板

我现在有一个变量content='123',还有一个按钮,点击按钮时,可以将content的内容复制到剪贴板上供我粘贴使用。

网上很多方法都是基于DOM元素定位的:
先选中文本框,再执行document.execCommand("Copy"),这个不适合我,因为我没有具体的文本框,只有变量名。

各位大神有没有好的方法或者插件,求推荐

阅读 11.9k
2 个回答

你也可以用下面的小套路,一样是'曲线救国'的实现方式,参考一下呗

// 复制变量copyVaule
handleCopy () {
    const copyVaule = 'http://baidu.com'
    this.$confirm(`复制此文章链接${copyVaule}, 是否继续?`, '复制', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }).then(() => {
      // 创建'虚拟'DOM
      const input = document.createElement('input')
      document.body.appendChild(input)
      input.setAttribute('value', copyVaule)
      input.select()
      if (document.execCommand('copy')) {
        document.execCommand('copy')
        this.$message({
          type: 'success',
          message: '复制成功!'
        })
      }
      // 删除'虚拟'DOM
      document.body.removeChild(input)
    }).catch(() => {
      this.$message({
        type: 'info',
        message: '已取消复制'
      })
   })
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题