可编辑/不可编辑内容复制方法大全

复制方法是开发中经常会用到的,在实现最近一个需求的时候发现了差异,常用的复制方法对不可复制内容无效,最终实现了功能,在此列出方法,记录一下

常用可粘贴内容的复制方法:

 copyHandle(name, data) { // 复制短链接
      const text = this.$refs[`${name}`]
      text.value = data
      text.select()
      document.execCommand('copy')
      this.$message({
        message: '复制成功!',
        type: 'success'
      })
    },

试了navigator.clipboard方法也可实现,但navigator对象不同页面包含的对象有差异,所以不是很推荐

 navigator.clipboard.writeText(data).then(() => {
       this.$message({
         message: '复制成功!',
          type: 'success'
         })
       })

不可复制内容复制
方法一:创建一个隐藏可编辑内容实现(较为笨拙)

function copyTextToClipboard(text) {
  // 创建一个临时的输入框
  const 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();
  textArea.setSelectionRange(0, text.length);
 
  // 执行复制命令
  let successful = false;
  try {
    successful = document.execCommand('copy');
  } catch (err) {
    console.error('Oops, unable to copy', err);
  }
 
  // 移除输入框
  document.body.removeChild(textArea);
 
  return successful;
}
 
// 使用示例
const textToCopy = "Hello, world!";
copyTextToClipboard(textToCopy);

方法二: 使用clipboard.js

  <el-button type="primary" size="mini" class="tag" @click="copyHandle(info.text)">复制链接</el-button>
  
import Clipboard from 'clipboard'

 copyHandle (data) {
      let clipboard = new Clipboard('.tag', {
        text: function () {
          return data
        }
      })
      clipboard.on('success', e => {
        this.$message({message: '复制成功', showClose: true, type: 'success'})
        // 释放内存
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        this.$message({message: '复制失败,', showClose: true, type: 'error'})
        clipboard.destroy()
      })
    },
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值