通过纯js代码实现将指定内容复制到粘贴板(兼容各主流浏览器)

通过纯js代码实现将指定内容复制到粘贴板(兼容各主流浏览器)

1.业务需求:
  • vue项目需要通过点击button按钮将指定内容复制到粘贴板中,且不引入第三方组件。
2.解决方案:
  • js写法如下(这里是利用了浏览器对选中的input标签的复制功能,且兼容各主流浏览器):

  •     // 复制操作函数(text:被复制的内容,可自定义)
          copyText(text) {
            let input = document.createElement('input') // 新增一个input
            input.style.position = 'relative' // 将它隐藏(注意不能使用display或者visibility,否则粘贴不上)
            input.style.zIndex = '-9'
            document.body.appendChild(input) // 追加
            input.value = text // 设置文本框的内容
            input.select() // 选中文本
            document.execCommand("copy") // 执行浏览器复制命令
            this.$message.success('已复制到粘贴板!')
          },
    

猜你喜欢

转载自blog.csdn.net/qq_34917408/article/details/107333894
今日推荐