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/

  • 相关阅读:
    jquerymobile动态添加元素之后不能正确渲染解决方法
    HTML5的新事件
    Visual Studio 2010扩展让JS与CSS实现折叠
    移动web开发--meta 之 viewport
    QR code二维码简介及Qrencode库的移植与使用
    http,socks5,socks4代理的区别
    关于代理服务器的原理及用法
    MTK的线刷工具Flash_Tool的常见错误码
    承认吧 --- SVN你根本就不会用,细说SVN的那点事儿
    SSH协议介绍 --- 有用
  • 原文地址:https://www.cnblogs.com/summer0319/p/7243465.html
Copyright © 2011-2022 走看看