美文网首页基础前端
随机密码生成器

随机密码生成器

作者: CondorHero | 来源:发表于2020-03-06 22:40 被阅读0次

    随机密码生成器主要难点有两个:

    • 第一个难点是把内容一键复制到剪切板
    • 第二个难点是随机产生数字,大小写字母,和特殊符号

    一、一键复制到剪切板

    一键复制
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>一键复制</title>
    </head>
    <body>
    <div>
        <input type="text" value="https://sebohuiav.com/video/play/id/11078.html" />
        <button>按我复制</button>
    </div>
    <script>
        const ipt = document.querySelector("input");
        const btn = document.querySelector("button");
        btn.onclick = function(){
                const textarea = document.createElement("textarea");
                textarea.value = ipt.value;
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand("copy");
                textarea.remove();
                alert("复制成功");
        };
    </script>
    </body>
    </html>
    

    二、随机密码函数

    随机大小写字母、数字、特殊符号。总共需要以下四个重要的函数:

    // 随机小写字母
    getRandomLower(){
        return String.fromCharCode(Math.floor(Math.random() * 26) + 97);
    }
    // 随机大写字母
    getRandomUpper(){
        return String.fromCharCode(Math.floor(Math.random() * 26) + 65);
    }
    //随机数字
    getRandomNumber(){
        return String.fromCharCode(Math.floor(Math.random() * 10) + 48);
    }
    // 随机符号
    getRandomSymbol(){
        const symbol = "!@#$%^&*(){}[]=<>/,.";
        return symbol[Math.floor(Math.random() * symbol.length)];
    }
    

    getRandomLower getRandomUpper getRandomNumber三个使用的 fromCharCode 主要是利用 ASCII 码表,大小写字符和数字是连贯的。特殊字符就不是连贯的了,具体观察下图的ASCII 码表:

    相关文章

      网友评论

        本文标题:随机密码生成器

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