H5点击复制到剪贴板

开发web端页面时,经常需要复制页面文本到剪贴板,比如页面展示订单号、物流单号等,我们使用js原生的document.execCommand实现复制功能

方法一:页面纯在输入框方法

1、在页面添加input框,给button绑定点击事件

<input type="text" id="copy-input" readOnly="readOnly" value="hello world">
<button @click="copy">复制</button>

添加readOnly只读属性,避免移动端弹出虚拟键盘

2、写copy方法

const input = document.getElementById('copy-input')
input.select()
document.execCommand('copy')

注意:

  • input框不能有disabled属性
  • 根据第一条扩展,input的width || height 不能为0;
  • input框不能有hidden属性

如果不想在页面上显示input输入框,可以使用创建input节点的方式,给value赋值,append到页面上,复制完了,再remove节点

方法二:纯js添加Dom元素并复制

const str = "需要复制的内容";
const inputo = document.createElement("input");
document.body.appendChild(inputo);
inputo.value = str;
inputo.setAttribute('readOnly', 'readOnly')
inputo.select();
document.execCommand("Copy");
document.body.removeChild(inputo);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值