js实现复制文本内容到剪切板

function copyUrl() {
        var Url2=document.getElementById("url").innerText;
        var oInput = document.createElement('input');
        oInput.value = Url2;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象
        document.execCommand("Copy"); // 执行浏览器复制命令
        oInput.style.display='none';
        alert('复制成功');
 }
 <div onclick="copyUrl()">
      <span class="fl">推广链接</span>
      <span  style="display: none;" id="url">http://......</span >
 </div>

 以上方法在微信中不兼容,可以使用clipboardjs插件,官网地址:https://clipboardjs.com/

 <!-- 1. Define some markup -->
    <input id="foo" type="text" value="hello">
    <button class="btn" data-clipboard-action="copy" data-clipboard-target="#foo">Copy</button>

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

    <!-- 3. Instantiate clipboard -->
    <script>
    var clipboard = new ClipboardJS('.btn');

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

    clipboard.on('error', function(e) {
        console.log(e);
    });
    </script>

 

posted @ 2018-07-18 14:08  Jade_g  阅读(362)  评论(0编辑  收藏  举报