文章正文

js-使用clipboard实现前端页面复制到粘贴板

【文章】2020-04-23

简介js-使用clipboard实现前端页面复制到粘贴板

轻量级js库clipBoard,官网地址https://clipboardjs.com/

使用步骤
第一步:引入js库 <script src="../dist/clipboard.min.js"></script>
第二步:定义标签(一般是触发复制的按钮)<button class="btn">Copy</button>
第三步:实例化clipboard,调用构造函数var clipboard = new Clipboard('.btn');

结合官方给的demo看一下几种场景

1.从变量赋值内容到剪贴板

var clipboard = new Clipboard('.btn', {
        text: function() {          
          return 'to be or not to be';
        }
    });

点击button,'to be or not to be'会粘贴到剪贴板

2.复制页面中p/input/textarea的内容

第一种方法构造函数里定义target

<p>hello</p>
var clipboard = new Clipboard('.btn', {
        target: function() {            
            return document.querySelector('p');
        }
    });

第二种方法在button里定义属性data-clipboard-target和data-clipboard-action

<p>hello</p>
<input id="foo" type="text" value="hello">
<button class="btn" data-clipboard-action="copy" data-clipboard-target="#foo">Copy</button>
<textarea id="bar">hello</textarea><button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">Cut</button>
<button class="btn" data-clipboard-action="copy" data-clipboard-target="p">Copy</button>var clipboard = new Clipboard('.btn');

clipboard还定义了复制成功/失败的回调函数

clipboard.on('success', function(e) {
        console.log(e);
    });clipboard.on('error', function(e) {
        console.log(e);
    });

打赏支持

感谢您的支持,加油!

打开微信扫码打赏,你说多少就多少

找书费时,联系客服快速获取!

扫码支持

在线客服8:30-22:30,若离线请留言!

获取教程,请联系在线客服!

扫码支持

在线客服8:30-22:30,若离线请留言!

热门阅读

找PDF电子书,太费时间?

  • 微信扫描二维码,让客服快速查找。
  • 在线客服8:30-22:00,若离线请留言!