美文网首页
关于ios中实现一键复制的问题

关于ios中实现一键复制的问题

作者: sanpangJin | 来源:发表于2023-03-09 11:54 被阅读0次

今天在项目中有一个一键复制的需求,再网上找了很多的资料,发现以下的方法很好的实现了

//一键复制

function copyLink(){

var e = document.getElementById("copy");

    e.select(); // 选择对象

    document.execCommand("Copy"); // 执行浏览器复制命令

    document.activeElement.blur();

}

满心欢喜的提交测试后,发现以上的代码再android中能完美的实现复制,但是在ios中确实不行的,并且在ios中还会有键盘被唤起一闪而逝的情况。

一点点的排查原因,终于发现实e.select()方法,ios不支持

寻找解决办法,终于找到了,借鉴了下面这位大神的方法
function selectText(textbox, startIndex, stopIndex) {

if(textbox.createTextRange) {//ie

        var range = textbox.createTextRange();

        range.collapse(true);

        range.moveStart('character', startIndex);//起始光标

        range.moveEnd('character', stopIndex - startIndex);//结束光标

        range.select();//不兼容苹果

    }else{//firefox/chrome

        textbox.setSelectionRange(startIndex, stopIndex);

        textbox.focus();

    }

}

相关文章

网友评论

      本文标题:关于ios中实现一键复制的问题

      本文链接:https://www.haomeiwen.com/subject/tvkjfqtx.html