一鍵復制文字到系統粘貼板(兼容蘋果瀏覽器)


思路:要想復制到剪貼板,必須先選中這段文字

<!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; 這會導致獲取不到文本內容。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM