document.execCommand 实现复制内容到粘贴板;不生效以及复制需要换行的解决方案

3,185 阅读1分钟

代码

copy(text) {
  const input = document.createElement('input');
  document.body.appendChild(input);
  input.setAttribute('value', text);
  input.select();
  document.execCommand('copy');
  console.log('复制成功');
  document.body.removeChild(input);
}

不生效的情况

  1. 事件需要由用户的实际操作触发,不能由纯 js 触发,而且触发事件到执行 execCommand 之间不能有异步任务。

    这个出于浏览器安全策略,无解。

  2. 触发复制事件的元素在 Modal 中,复制不生效。

    解决办法:将 document.body.appendChild(input) 改成 ref?.current.appendChild(input),然后把 ref 赋给 Modal 内包裹的一个 div 中,就能解决 range 的问题。盲猜是因为 Modal 脱离了文本流,所以绑定的事件就拿不到外部的 document.body 里的 input 的内容,让 input 也脱离文本流就行了。

复制的文本需要换行的问题

input 的内容不支持换行,但是普通标签又没有 select 事件(一般是 onselect),这时就要用 textarea,然后将要换行的地方插入 '\r\n',同时赋值不能使用 input.setAttribute('value', text),改成 input.value = text 即可。

copy(text) {
  const input = document.createElement('textarea');
  document.body.appendChild(input);
  input.value = text;
  input.select();
  document.execCommand('copy');
  console.log('复制成功');
  document.body.removeChild(input);
}