js点击复制文本到粘贴板(vue可用,兼容ios)

在移动端,为了方便客户查询订单号和运单号,需要点击复制文本到粘贴板功能。收罗了很多知识点,总结了两种方法

一、方法一

js自带execCommand方法可以做复制

第一种,利用input,先创建一个input,选取复制后,再销毁
//点击按钮,这是vue
<div @click="copy(i.goods_oid)">
   <span>订单号(复制):</span><span>{{ i.goods_oid }}</span>
</div>
	//js函数,e就是接受的订单号,vue
    copy(e) {
      let input = document.createElement("input");
      input.value = e;
      document.body.appendChild(input);
      input.select();
      document.execCommand("Copy");
      document.body.removeChild(input);
      // console.log(document.execCommand("Copy"))
      if (document.execCommand("Copy") == true) {
        alert(`订单号复制成`);
      }
    },
二、方法二
第二种,利用input的readonly的只读属性,不能用disable,disable不能读取value
<div @click="copy2()">
	<span>子订单号(复制):</span>
    <input type="text" :value="i.goods_oid"  readonly id="copyText" style="border: none;"/>
</div>
    copy2() {
      let text = document.getElementById("copyText");
      text.select();
      document.execCommand("Copy");
      // console.log(document.execCommand("Copy"))
      if (document.execCommand("Copy") == true) {
        alert(`订单号复制成`);
      }
    },
三、方法三
三、textarea输入框也是同理可得。具体我就不写了。与input代码一样,修改下就能用
创建新的和利用复制
四、方法四(兼容ios)
	let value = "我是被copy的内容"
    let oInput = document.createElement("input");
    oInput.value = value;
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {//兼容ios
      if (!document.execCommand("Copy")) {
        oInput.setSelectionRange(0, oInput.value.length);
      }
    }
    document.execCommand("Copy"); // 执行浏览器复制命令
    document.body.removeChild(oInput);
    return new Promise((resolve,reject)=>{
        if (document.execCommand("Copy")) {
            resolve(value);
        }else{
            reject(value);
        }
    })

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值