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

對前端技術保持學習愛好者。我會經常分享自己所學所看的乾貨,在進階的路上,共勉!歡迎關注公衆號共同學習。   

                                                    

 

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