zoukankan      html  css  js  c++  java
  • 一键复制文字到系统粘贴板(兼容苹果浏览器)

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

    <!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; 这会导致获取不到文本内容。

  • 相关阅读:
    python+selenium初学者常见问题处理
    pycharm的这些配置,你都知道吗
    巧用浏览器F12调试器定位系统前后端bug
    dsu + lca
    indeed2017校招在线编程题(网测)三
    rolling hash
    ac自动机
    indeed 第二次笔试题
    vmware以及schlumberger题解
    2017 google Round C APAC Test 题解
  • 原文地址:https://www.cnblogs.com/myIvan/p/10275625.html
Copyright © 2011-2022 走看看