js實現復制文字到剪切板


 

方法一: 使用 js 實現

 1 function copyToClipboard (text) {
 2     if(text.indexOf('-') !== -1) {
 3         let arr = text.split('-');
 4         text = arr[0] + arr[1];
 5     }
 6     var textArea = document.createElement("textarea");
 7       textArea.style.position = 'fixed';
 8       textArea.style.top = '0';
 9       textArea.style.left = '0';
10       textArea.style.width = '2em';
11       textArea.style.height = '2em';
12       textArea.style.padding = '0';
13       textArea.style.border = 'none';
14       textArea.style.outline = 'none';
15       textArea.style.boxShadow = 'none';
16       textArea.style.background = 'transparent';
17       textArea.value = text;
18       document.body.appendChild(textArea);
19       textArea.select();
20 
21       try {
22         var successful = document.execCommand('copy');
23         var msg = successful ? '成功復制到剪貼板' : '該瀏覽器不支持點擊復制到剪貼板';
24        alert(msg);
25       } catch (err) {
26         alert('該瀏覽器不支持點擊復制到剪貼板');
27       }
28 
29       document.body.removeChild(textArea);
30 }

 

 

方法二:使用clipboard.min.js 實現

  1: 在vue項目中,首先引入clipboard.min.js 類庫

  2: 利用vue鈎子在頁面加載完成后初始化clipboard對象

1         mounted(){
2             new Clipboard($(this.$el).find('.btn-copy')[0]);
3             new Clipboard($(this.$el).find('.btn-copy')[1]);
4         }

  3:html頁面的復制按鈕添加屬性

 span.btn-copy.copy( @click="copyclipboard",data-clipboard-text="這里面是復制的內容,可以使用變量代替") 點擊復制  

 

 

 

 

在非vue項目中也是一樣,引入類庫后初始化Clipboard對象就可以使用了

下面貼出一段使用案例源碼

  <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>target-div</title>
 </head>
 <body>
     <!-- 1. Define some markup -->
     <div>hello</div>
     <button class="btn" data-clipboard-action="copy" data-clipboard-target="div">Copy</button>
 
     <!-- 2. Include library -->
     <script src="../dist/clipboard.min.js"></script>
 
     <!-- 3. Instantiate clipboard -->
     <script>
     var clipboard = new Clipboard('.btn');
 
     clipboard.on('success', function(e) {
         console.log(e);
     });
 
     clipboard.on('error', function(e) {
         console.log(e);
     });
     </script>
 </body>
 </html>

 

 

可以參考github上的源碼,寫的很清晰

https://github.com/zenorocha/clipboard.js/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM