zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    BZOJ 1016 最小生成树计数(矩阵树定理)
    sdoi2013 spring(hash+容斥)
    51nod 1301 集合异或和(DP)
    51nod 1576 Tree and permutation(树的重心+dfn序)
    BZOJ 4145 [AMPPZ2014]The Prices (状压DP)
    BZOJ 2260 商店购物(最小树形图)
    BZOJ 4006 [JLOI2015]管道连接(斯坦纳树+子集DP)
    BZOJ 2595 [Wc2008]游览计划(斯坦纳树)
    BZOJ 5180 [Baltic2016]Cities(斯坦纳树)
    51nod 1392 装盒子(费用流)
  • 原文地址:https://www.cnblogs.com/summer0319/p/7243465.html
Copyright © 2011-2022 走看看