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

本人遇到插件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("复制成功!");

      }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容