前端点击复制文字,兼容Android和ios。

1.原生方法:
如下方法,可以实现浏览器的复制文本功能,但是因为execCommand已经被放弃,但是还没执行,好像在ios15之后,ios不支持了,导致,ios上无法复制。

copyWord(word){
            const textArea = document.createElement('textArea')
            textArea.value = word;
            //添加到dom节点中
            textArea.style.width = 0
            textArea.style.position = 'fixed'
            textArea.style.left = '-999px'
            textArea.style.top = '10px'
            textArea.setAttribute('readonly', 'readonly')
            document.body.appendChild(textArea)
            textArea.select()
            
            document.execCommand('copy')
            // 移除元素
            document.body.removeChild(textArea);
        }

2.引用组件
运行

npm install --save vue-clipboard2 

在main.js中引用

import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)

使用方法:

this.$copyText(res.data?.data?.url || '').then((e) => {
	this.$toast.success('复制链接成功');
 }, (e) => {
     this.$toast.error('复制链接失败');
 })```
 首先需要使用vue-clipboard2实现的功能是:复制通过后台得到的数据,vue-clipboard2在安卓和pc端都没有问题,但是到了ios系统,不管是safari,微信,都会没有效果。
查阅了一下资料说是因为this.$copyText()写在axios这个异步方法里,而vue-clipboard2主页上说这个方法不可以写在异步方法里。
解决办法是给this.$copyText()外面包一个定时器,代码如下:

setTimeout(()=>{
this.KaTeX parse error: Expected '}', got 'EOF' at end of input: … this.toast.success(‘复制链接成功’);
}, (e) => {
this.$toast.error(‘复制链接失败’);
})
},100)

成功解决了这个问题!
最后提一句,本来我是使用原生的document.execCommand("copy")来实现复制的。

[参考链接:](https://blog.csdn.net/weixin_43299180/article/details/112473038)
[参考链接:](https://juejin.cn/post/7129718241726824461)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值