JS实现复制粘贴的方式

最近在项目中遇到了需要复制粘贴的功能,虽然是个简单的小功能,我竟然没做过,所以根据查找的资料还有实践在这里总结一下;

JS实现复制粘贴方式:

  • 原生通过document.execCommand(‘copy’)的方式实现
  • 使用第三方框架clipboard的方式实现
  • IE大神
一、execCommand方式
  • document.execCommand(),文档对象的 execCommand方法允许运行命令来操纵可编辑区域的内容,具体可以查看这里
  • 只需要选中要复制的内容,执行document.execCommand(‘copy’, false, null)就好了。execCommand里可以跑很多例如paste等方法,第一个参数是方法名,第二个是是否展示默认ui,第三个是可选参数列表,对copy来说后两个都用不到。
  • 这个方法指拷贝当前选中内容到剪贴板,返回值为一个 bool 值, 如果返回值为 false 则表示操作不被支持或未被启用。
    很遗憾的是这个方法的浏览器兼容性一般,IE 仅支持 8 以上的版本。
  • 主要是通过 class和id 来复制 a标签中的 href,把复制好的内容放到 生成的input标签中,然后复制结束把 input标签给remove。
  • 第一次点击不生效,需要点击两次,暂时不解决(我没有遇到)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>constructor-nodelist</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<button class="copy_file" onclick="copyText('copy_file')">点我复制</button>
<a id="copy_file" href="复制内容"></a>
function copyText(file) {
    const btn = document.querySelector('.'+file);
    var copy_val = document.getElementById(file)
    var copy_file = copy_val.getAttribute("href");
    btn.addEventListener('click',() => {
        const input = document.createElement('input');
        document.body.appendChild(input);
        input.setAttribute('value', copy_file);
        input.select();
        if (document.execCommand('copy')) {
            document.execCommand('copy');
            alert("复制成功!","success");
        }
     document.body.removeChild(input);
    })
}
</script>
</body>
// 项目中工具函数的用法
export const copy = function(value) {
  return new Promise(resolve => {
    let copyTextArea = null
    try {
      copyTextArea = document.createElement('textarea')
      copyTextArea.style.height = '0px'
      copyTextArea.style.opacity = '0'
      copyTextArea.style.width = '0px'
      document.body.appendChild(copyTextArea)
      copyTextArea.value = value
      copyTextArea.select()
      document.execCommand('copy')
      resolve(value)
    } finally {
      if (copyTextArea && copyTextArea.parentNode) {
        copyTextArea.parentNode.removeChild(copyTextArea)
      }
    }
  })
}
二、clipboard方式
  • 主要是看文档 实现复制,粘贴,剪切等功能。
  • clipboard和Fastclick冲突,导致点击两次才能复制。解决方案:加一个名为“needsclick”的类名<button id="copyDom" class="needsclick ">点击复制</p>
methods: {
  initClipboard (copyDom) {
       let clipboard = new Clipboard(copyDom, {
           text: function () {
               return document.getElementById(copyDom).innerText;
           }
       });
       clipboard.on('success', function (e) {
           console.log('Action:', e.action);
           console.log('Text:', e.text);
           console.log('-- 复制成功 --');
           e.clearSelection();
       });
       clipboard.on('error', function (e) {
           console.log(e);
       });
   },
   // 点击复制
   initCopyDom () {
       this.initClipboard('#copyDom');
   },
}
三、IE

其他浏览器出于安全的考虑禁止js访问操作系统粘贴板;

if(window.clipboardData){
  //清空操作系统粘贴板
  window.clipboardData.clearData();
  //将需要复制的内容复制到操作系统粘贴板  
  window.clipboardData.setData("Text", "要复制的内容");
}
四、有问题会继续更新
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值