<button id="click">点击复制链接</button>
<div id="copyDom"></div>
copyUrl(){
if((navigator.userAgent.match(/(iPhone|iPod|iPad);?/i))){
//ios系统
window.getSelection().removeAllRanges();//这段代码必须放在前面否则无效
let inputDom =document.createElement('input');
let copyDom=document.getElementById("copyDom");//要复制文字的节点
copyDom.appendChild(inputDom);// 把标签添加给body
inputDom.style.opacity = 0;//设置input标签设置为透明(不可见)
inputDom.value = "https://www.baidu.com/"; // 修改文本框的内容
let range = document.createRange();
// 选中需要复制的节点
range.selectNode(inputDom);
// 执行选中元素
window.getSelection().addRange(range);
inputDom.select();
inputDom.setSelectionRange(0,inputDom.value.length);//适配高版本ios
// 执行 copy 操作
let successful = document.execCommand('copy');
let messageText =successful?'请将此链接复制至手机或电脑浏览器打开并完成下载。':'链接复制失败!'
alert(messageText)
// 移除选中的元素
window.getSelection().removeAllRanges();
copyDom.removeChild(inputDom)
}else{
//其他系统
let inputDom =document.createElement('input');
let copyDom = document.getElementById('copyDom')
copyDom.appendChild(inputDom);// 把标签添加给body
inputDom.style.opacity = 0;//设置input标签设置为透明(不可见)
inputDom.value = "https://www.baidu.com/"; // 修改文本框的内容
inputDom.select(); // 选中文本
// 执行选中元素
let successful = document.execCommand("copy"); // 执行浏览器复制命令
let messageText =successful?'请将此链接复制至手机或电脑浏览器打开并完成下载。':'链接复制失败!'
alert(messageText)
copyDom.removeChild(inputDom)
}
}
var clickDom =document.getElementById('click')
clickDom.onclick=function(){
copyUrl()
}
1、测试过程中使用.select()方法在iphone6s上不能正常复制,所以将ios特别分出使用了.createRange()。
2、由于document.execCommand(“copy”)这个方法已过时:
推荐使用一个插件clipboard使用方法