JS复制文本到粘贴板,前端H5移动端点击按钮复制文本

<span id="codeNum">FTYHDSDW</span>
<span class=" code-btn" id="codeBtn" data-clipboard-target="#input">复制</span>

js代码

<script type="text/javascript">
  function copyArticle(event) {
        const range = document.createRange();
        range.selectNode(document.getElementById('codeNum'));
 
        const selection = window.getSelection();
        if(selection.rangeCount > 0) selection.removeAllRanges();
        selection.addRange(range);
        document.execCommand('copy');
        alert("复制成功!");
      }
    document.getElementById('codeBtn').addEventListener('click', copyArticle, false);
    
</script>

源地址:https://www.jianshu.com/p/6ec9c72dc5eb

posted @ 2019-09-24 15:08  11个条子  阅读(2560)  评论(0编辑  收藏  举报