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

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

作者: 漂亮假动作 | 来源:发表于2019-08-27 16:10 被阅读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("复制成功!");

      }

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/dxieectx.html