在移动端,为了方便客户查询订单号和运单号,需要点击复制文本到粘贴板功能。收罗了很多知识点,总结了两种方法
一、方法一
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);
}
})