html:
<input readOnly="true" style="outline: none;border: 0px; color: rgba(0,0,0,0.0);position: absolute;left:-200px; background-color: transparent" id="biao1" value=""/>
<div id="biaoios" style="position: absolute;left:-200px; color: rgba(0,0,0,0);background-color: transparent" ></div>
<button type="button" onclick="copy()" >复制</button>
js:
function copy(){
if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {//区分iPhone设备
var text = document.getElementById('biaoios');
//获取隐藏的input,并写入text内容,在进行复制
var input = document.getElementById("biao1");
input.value = text.innerHTML;
input.select();
input.setSelectionRange(0, input.value.length); //兼容ios
document.execCommand("Copy");
input.blur();
alert("复制成功")
}else{
var Url2=document.getElementById("biao1");//要复制文字的节点
Url2.select(); // 选择对象
//document.execCommand("Copy"); // 执行浏览器复制命令
$("#biao1").blur();
if(document.execCommand('copy', false, null)){
var successful = document.execCommand('copy');// 执行浏览器复制命令
alert("成功")
}else{
alert("失败")
};
}
}
如何第一个方法copy() 不行,试试以下的,亲测 直接复制就能用
function newCopy(){
$("#biao1").val("要复制的内容");//安卓
if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {
var el = document.createElement('input');
el.value = "要复制的内容";//要复制的内容
el.style.opacity = '0';
document.body.appendChild(el);
var editable = el.contentEditable;
var readOnly = el.readOnly;
el.contentEditable = true;
el.readOnly = false;
const range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
el.setSelectionRange(0, 999999);
el.contentEditable = editable;
el.readOnly = readOnly;
var ret = document.execCommand('copy');
el.blur();
if(ret){
alert("成功")
}else{
alert("失败")
}
}else{
var Url2=document.getElementById("biao1");
Url2.select(); // 选择对象
$("#biao1").blur();
if(document.execCommand('copy', false, null)){
var successful = document.execCommand('copy');
alert("成功")
}else{
alert("失败")
};
}
}
最好检测一下标签的样式,不要被其他样式影响而被覆盖按钮,造成无法点击的情况;