想想自己也学了很久的前端的技术了,这两天在自己设计一个网站的时候,突然想到了登录验证码的这个东西,用了这个比较简单的随机码生成,大家如果有需要也可以用来参考。


代码展示(部分内容使用了jquery):

HTML部分:

<div class="user_code">
     <input type="text" name="code" placeholder="请输入验证码">
     <div class="code_tip"></div>
     <div class="code_tip_box" title="点击刷新验证码"></div>
</div>

CSS部分

.user_code {
    position: relative;
    width: 80%;
    height: 36px;
    margin: 0 auto 20px;
    overflow: hidden;
}
.user_code input {
    float: left;
    width: 48%;
    height: 35px;
    background: none;
    text-align: center;
    border-bottom: 1px solid #000;
}
.user_code .code_tip,
.user_code .code_tip_box {
    float: right;
    width: 48%;
    height: 35px;
    border: 1px solid #aaa;
    text-align: center;
    line-height: 33px;
    font-size: 18px;
    background: none;
}
.user_code .code_tip_box {
    position: absolute;
    right: 0;
    top: 0;
    border: none;
    background: rgba(200, 200, 200, 0.2);
    cursor: pointer;
}

JavaScript部分

// 验证码写入到指定位置
$(".code_tip").text(code(4));
$(".code_tip_box").click(() => {
    $(".code_tip").text(code(4));
});
/* 自动生成随机验证码 */
function code(code_length) {
    let code_tips = "";
    let content = [];
    let num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    /* 重复数字 */
    content = content.concat(num);
    /* 大写字母 */
    for (let a = 65; a <= 90; a++) {
        content.push(String.fromCharCode(a));
    };
    /* 重复数字 */
    content = content.concat(num);
    /* 小写字母 */
    for (let b = 97; b <= 122; b++) {
        content.push(String.fromCharCode(b));
    };
    /* 重复数字 */
    content = content.concat(num);
    /* 输出长度 */
    for (let c = 0; c < code_length; c++) {
        code_tips += content[Math.floor(Math.random() * content.length)];
    };
    return code_tips;
};

效果展示:

简单的随机乱码生成(验证码生成)| HTML


关于这里为什么要把数字的部分重复几遍的说明:

大写字母数量:26

小写字母数量:26

数字数量:10 * 3 = 30

本质上还是为了在输出的时候能够让字母和数字的输出相对来说平均一些

但是就有可能出现情况是数字的输出数量比字母要多

各位在使用的时候,可以将两行用于重复数字的代码删除


以上的代码部分均是从自己正在制作的一个网页中截取出来的,CSS代码可能和各位的实际需求并不适配,根据需要自行修改就好。


完整代码已上传至git:

gitee:个人代码分享gitee

github:个人代码分享github

以上内容均仅作参考,原创作品,严禁转载。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。