js 点击按钮复制文本方法

点击按钮,执行复制指定位置的文本,具体实现方案如下:

1、添加点击事件

<span class="copyMa" @click="copy()">点击复制</span>

2、copy的实现方法(未优化)

copy(){
     let random = this.$refs.randomCodeRef.innerHTML;
     const input = document.createElement('input');
     document.body.appendChild(input);
     input.setAttribute('value',random);
     input.select();
     document.execCommand("Copy");
},

3、以上方法点击一次就会执行一次复制,也就是说会在body里创建一个input标签,点击n次就会创建n个,不符合逻辑,做以下优化,复制完之后将创建出来的input的dom移除(优化方案)

copy(){
     let random = this.$refs.randomCodeRef.innerHTML;
     const input = document.createElement('input');
     document.body.appendChild(input);
     input.setAttribute('value',random);
     input.setAttribute('create',1);
     input.select();
     document.execCommand("Copy");
     var list=document.getElementsByTagName('input')
     var inputList = Array.prototype.slice.call(list)
     inputList.forEach((item)=>{
         if(item.getAttribute('create'))document.body.removeChild(item);
     });
},

注意:如果复制的文本需要换行展示,就不能使用上面的动态创建 input 标签,因为 input 标签是单文本标签,不会换行,也就是\r\n不起作用,但是\t空格还是起作用的,所以建议使用 textarea 所以如果你复制的文本需要换行展示,就可以参考以下方法

//如下换行设置 \r\n

copy(){
     let copyText = "分享链接:\r\n"+this.shareQrcodeUrl+"\r\n";

     copyText = copyText +"分享码:"+this.shareCode+"\r\n";

     const input = document.createElement('textarea');
     document.body.appendChild(input);
     input.innerHTML = copyText;
     input.setAttribute('code',1);
     input.select();
     document.execCommand("Copy");

     var list = document.getElementsByTagName('textarea');
     var inputList = Array.prototype.slice.call(list);
     inputList.forEach((item)=>{
            if(item.getAttribute('code'))document.body.removeChild(item);
     });
},

 

  • 8
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值