function copyLinkToClipBoard() { if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {//区分iPhone设备 window.getSelection().removeAllRanges();//这段代码必须放在前面否则无效 var Url2=document.getElementById("testinput");//要复制文字的节点 Url2.value=window.location.href; var range = document.createRange(); // 选中需要复制的节点 range.selectNode(Url2); // 执行选中元素 window.getSelection().addRange(range); // 执行 copy 操作 var flag = document.execCommand('copy'); // 移除选中的元素 window.getSelection().removeAllRanges(); Url2.blur(); if(flag){ weui.alert("复制成功"); } }else{ var Url2=document.getElementById("testinput");//要复制文字的节点 Url2.select(); // 选择对象 Url2.blur(); var flag = document.execCommand('copy'); // 执行浏览器复制命令 if(flag){ weui.alert("复制成功"); } } }
<input type="text" id="testinput" style="opacity: 0;">