clipboard.js实现复制链接功能

2019-01-29  本文已影响0人  xingxixi

现有的常用方案有两种:
  一:使用原生javascript中window.clipboardData实现复制到剪贴板功能;
  二:使用Zero Clipboard库;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>target-div</title>
</head>
<body>
    <!-- 1. Define some markup -->
<button id="copyUrl" data-clipboard-target="#copyUrl" data-clipboard-action="copy" onClick="copyUrl()" class="btn btn-white btn-xs">复制链接</button>

    <!-- 2. Include library -->
    <script src="../dist/clipboard.min.js"></script>

    <!-- 3. Instantiate clipboard -->
    <script>
        function copyUrl(){
            var layer = layui.layer;
             var _val=document.location.href;
             console.log(document.location.href);
          var clipboard = new ClipboardJS('#copyUrl', {
            text: function() {
                   layer.alert('复制成功!', {icon: 1});
                   return _val;
              }
        });
        }
    </script>
</body>
</html>

注意:使用中var clipboard = new Clipboard('#copyUrl');出现了错误提示Uncaught ReferenceError: Clipboard is not defined,原因为Clipboard2.0版本应使用var clipboard=new ClipboardJS('#copyUrl');

        function copyUrl(){
            layui.use('layer', function () {
                var layer = layui.layer;
                var clipboard = new ClipboardJS('#copyUrl', {
                    text: function() {
                        return window.location.href;
                    }
                });
                clipboard.on("success", function(e) {
                    console.log("ok");
                    layer.msg("复制成功",{icon:1, time: 1000});
                    clipboard.destroy();
                });
                clipboard.on("error", function(e) {
                    console.log("fail");
                });
                document.getElementById('copyUrl').click();  //解决clipboard二次点击生效问题
                clipboard.destroy();

            });
        }
上一篇下一篇

猜你喜欢

热点阅读