h5页面点击按钮实现复制文本功能

2019-08-27  本文已影响0人  漂亮假动作

本人遇到插件ClipboardJS在IOS里不生效的情况很折磨人后,改用另一种写法

按钮

<button class="copy"onclick="copyArticle('你好')">复制</button>

方法(val是要复制的文本值,亲测可用包括安卓,ios,pc)

function copyArticle(val) {

    var input = document.createElement('input');

    input.setAttribute('id','copyId');

    input.value= val

    document.querySelector('body').appendChild(input)

          const range = document.createRange();

          range.selectNode(document.getElementById('copyId'));

          const selection = window.getSelection();

          if(selection.rangeCount> 0)selection.removeAllRanges();

          selection.addRange(range);

          document.execCommand('copy');

          document.getElementById('copyId').remove()

          alert("复制成功!");

      }

上一篇 下一篇

猜你喜欢

热点阅读