JS 复制内容到剪贴板

本文内容如下:

  • 使用 clipboard.js 插件
  • 使用 document.execCommand() 原生方法
  • 复制图片

1.使用 clipboard.js 插件

该插件使用比较简单,兼容性较好。具体使用方法见:github clipboard.js

兼容性:
在这里插入图片描述

2.使用 document.execCommand() 原生方法

直接看代码:

/**
 * 复制内容
 * @param {String} value 需要复制的内容
 * @param {String} type 元素类型 input, textarea
 */
export function copyContent(value, type = 'input') {
  const input = document.createElement(type);
  input.setAttribute('readonly', 'readonly'); // 设置为只读, 防止在 ios 下拉起键盘
  // input.setAttribute('value', value); // textarea 不能用此方式赋值, 否则无法复制内容
  input.value = value;
  document.body.appendChild(input);
  input.setSelectionRange(0, 9999); // 防止 ios 下没有全选内容而无法复制
  input.select();
  document.execCommand('copy');
  document.body.removeChild(input);
}

这里主要解决了 ios 下的 bug,以及使用 textarea 来解决换行内容的复制。

兼容性:
在这里插入图片描述

3.复制图片(移动端可能达不到想要的效果)

复制一张图片
/**
 * 复制网络图片
 */
export function copyImg(imgUrl: string) {
  fetch(imgUrl)
    .then(res => res.blob())
    .then(blob => {
      toDataURL(blob).then(base64 => {
        navigator.clipboard.write([new ClipboardItem({ 'image/png': dataURLToBlob(base64, 'image/png') })])
      })
    })
}
复制多张图片
/**
 * 复制文字或图片
 * (通过创建元素并选中的方式实现复制)
 */
export function copyInfo(sets: { txts?: string | string[]; imgs?: string | string[]; callback?: () => void }) {
  let imgDiv = document.createElement('div')
  imgDiv.id = '__imgDiv'
  imgDiv.setAttribute('style', 'z-index: -1;position: fixed;')
  let child = ''
  if (sets.txts) {
    if (typeof sets.txts === 'string') {
      child += `<span>${sets.txts}</span>`
    } else {
      sets.txts.forEach(item => {
        child += `<span>${item}</span>`
      })
    }
  }
  if (sets.imgs) {
    if (typeof sets.imgs === 'string') {
      sets.imgs = sets.imgs.indexOf('https') > -1 ? sets.imgs.replace('https', 'http') : sets.imgs
      child += `<img src="${sets.imgs}" />`
    } else {
      sets.imgs.forEach(item => {
        item = item.indexOf('https') > -1 ? item.replace('https', 'http') : item
        child += `<img src="${item}" />`
      })
    }
  }
  imgDiv.innerHTML = child
  document.body.insertBefore(imgDiv, document.body.lastChild)
  let dom = document.getElementById('__imgDiv')
  // console.log(dom)
  if (window.getSelection) {
    // chrome等主流浏览器
    let selection = window.getSelection()
    let range = document.createRange()
    range.selectNodeContents(dom!)
    selection?.removeAllRanges()
    selection?.addRange(range)
    // @ts-ignore
  } else if (document.body.createTextRange) {
    // ie
    // @ts-ignore
    let range = document.body.createTextRange()
    range.moveToElementText(dom)
    range.select()
  }
  document.execCommand('copy')
  window.getSelection()?.removeAllRanges()
  imgDiv.parentNode?.removeChild(imgDiv)
}


// 使用
copyInfo({
  imgs: [
 	'https://xxx.test.png',
    'https://xxx.test.png'
  ]
})
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值