前端复制功能

前端复制功能

在很多场景我们见到很多一键复制的操作(如下图),最近一个react项目中需要实现一个点击复制的功能,拿出来和道友分享一下。
这里写图片描述
实现代码

 function copyText(value) {
  document.designMode = 'on';
  const input = document.createElement('input');
  document.body.appendChild(input);
  input.setAttribute('value', value);
  input.setAttribute('readonly', 'readonly')
  input.select();
  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    // console.log('Copy email command was ' + msg);
    if(!successful) {
        throw new Error("copy failed");
    }
    Message.success({
      content: "复制成功!"
    });
  } catch (err) {
    console.log('Oops, unable to copy');
    Message.error({
      content: "复制失败,请重试或手动复制"
    })
  }
  document.body.removeChild(input);
  document.designMode = 'off'
}

实现函数如上所示,designMode说明见参考链接

参考链接

  1. 原生JavaScript实现复制/粘贴
  2. clipboard.js
  3. MDN exceCommand 介绍
  4. designMode介绍

猜你喜欢

转载自blog.csdn.net/wangweiren_get/article/details/81710355