一键复制文字到系统粘贴板(兼容苹果浏览器)

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>一键复制(兼容苹果手机)</title>
</head>
<body>
    <input style="border:none;" type="text" readonly="" id="copy_text" value="123456">
    <span style="font-weight: bold; cursor:pointer;" id="clip_button" onlick="copyNum()" >点击复制</span>
    <script>
        // 思路:要想复制到剪贴板,必须先选中这段文字。
        function copyNum(){
            var copy_text=document.getElementById("copy_text");
            var text=copy_text.value;
            var valueLength = text.length;
            selectText(copy_text, 0, valueLength);
            if(document.execCommand('copy', false, null)){
                document.execCommand('copy', false, null)// 执行浏览器复制命令
            }else{
                console.log("不兼容");
            }
        }
        
        // 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{
                //兼容苹果
                textbox.setSelectionRange(startIndex, stopIndex);
                textbox.focus();
            }
        }
    </script>
</body>
</html>

通过自己构建一个选择文本的函数来兼容苹果浏览器。

提示:如果你复制的文本框想要隐藏,可以用opacity:0; 千万别用display:none; 这会导致获取不到文本内容。

猜你喜欢

转载自www.cnblogs.com/myIvan/p/10275625.html
今日推荐