解决js在ios,safari浏览器下无法复制的问题

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("失败")
        };
    }
}

最好检测一下标签的样式,不要被其他样式影响而被覆盖按钮,造成无法点击的情况;

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值