js简单实现复制到剪贴板功能,execCommand,H5,web

参考文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand

应用场景:在页面中,实现一键点击复制文案功能,免去用户手动复制

1、先在文档流中新建一个临时的 input 输入框元素

const Ele_input = document.createElement('input');
document.body.appendChild(Ele_input);

2、给该元素设置值,并选中(值即需要复制的文案)

Ele_input.setAttribute('value', '要复制的文案');
Ele_input.select(); // 选中输入框中需要复制的文案

3、调用 document.execCommand 方法来实现将文案复制到剪贴板

if(document.execCommand('copy')){
  document.execCommand('copy');
  alert('复制成功')
}else{
  alert('复制失败,请手动复制');
}

4、删除临时的 input 元素

document.body.removeChild(Ele_input);

使用时将以上代码封装到一个方法中即可

function copy(v){
  const Ele_input = document.createElement('input');
  document.body.appendChild(Ele_input);
  Ele_input.setAttribute('value', v);
  Ele_input.select();
  if(document.execCommand('copy')){
    document.execCommand('copy');
    alert('复制成功')
  }else{
    alert('复制失败,请手动复制');
  }
  document.body.removeChild(Ele_input);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容