jquery 一键复制功能,兼容苹果

有做过一个项目,做好之后交给客户,客户用的是苹果手机,不料给我反馈回来一键复制功能 不能使用。

这是我原来的代码 可以引入https://code.jquery.com/jquery-3.3.1.min.js
html:

微信: <input class="mytxt" id="xmid" value="13521423628" readonly="readonly" unselectable="on"></input>

<span class="copyname">(点击复制)</span>

js:

<script>

    // 一键复制 只针对安卓 select()不兼容苹果

    $('.copyname').click(function () {

        var dd = $('.mytxt');

        dd[0].select();

        document.execCommand("Copy");

        alert("复制成功!")

    });

</script>

对,这段代码可以实现一键复制的效果,但只在安卓手机上生效,因为select()在苹果上不生效。这也算是苹果的一个坑吧。

所以换了一种写法,兼容苹果的,以后都用这个了,有需要的朋友可以看下 , html代码也变了哦

html:

微信: <input class="mytxt" id="xmid" value="13521423628" readonly="readonly" unselectable="on"></input>

<span onClick="copyNum()">(点击复制)</span>

js:

<script>

    // 思路:要想复制到剪贴板,必须先选中这段文字。

    function copyNum() {

        var NumClip = document.getElementById("xmid");

        var NValue = NumClip.value;

        var valueLength = NValue.length;

        selectText(NumClip, 0, valueLength);

        if (document.execCommand('copy', false, null)) {

            document.execCommand('copy', false, null) // 执行浏览器复制命令

            alert("复制成功!");

        } else {

            alert("不兼容");

        }

    }

    // input自带的select()方法在苹果端无法进行选择,所以需要自己去写一个类似的方法

    // 选择文本。createTextRange(setSelectionRange)是input方法

    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();

        }

    }

</script>

猜你喜欢

转载自blog.csdn.net/lyq_chengxu99/article/details/89351864
今日推荐