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);
     });
},

 

交流
可添加qq群共同进阶学习: 进军全栈工程师疑难解  群号:   856402057

对前端技术保持学习爱好者。我会经常分享自己所学所看的干货,在进阶的路上,共勉!欢迎关注公众号共同学习。   

                                                    

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章