h5复制到剪切板

参考地址:https://segmentfault.com/a/11...
demo地址:http://codepen.io/JimmyVV/pen...
单独访问没问题,只要放进项目,第一次报错,复制不成功,第二次之后就可以了

clipboard.png

// 复制链接地址并关闭分享且提醒
    var aEle = document.querySelector('#copy');
        aEle.addEventListener('click',function(){
            var copyDOM = document.querySelector('#selector');
            var range = document.createRange();  
              range.selectNode(copyDOM);
              window.getSelection().addRange(range);
              var successful = document.execCommand('copy');  
              try {  
                // Now that we've selected the anchor text, execute the copy command  
                
                var msg = successful ? 'successful' : 'unsuccessful';  
                console.log('Copy email command was ' + msg);  
              } catch(err) {  
                console.log('Oops, unable to copy');  
              }

              // Remove the selections - NOTE: Should use
              // removeRange(range) when it is supported  
              window.getSelection().removeAllRanges();  
        },false);
阅读 5.3k
1 个回答
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);

addRange之前先remove

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏