简单实现网页验证码

实现功能:

1.通过页面刷新以及鼠标点击验证码区域可以实现验证码的刷新;

2.实现常规验证码的操作。如果你不输入验证码会告诉你让你输入;如果输入错误也会提醒你;当你输入正确无误会庆祝哦!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>验证码</title>
    <style>
        .code {
            width: 120px;
            height: 50px;
            background-color: pink;
            display: inline-block;
            text-align: center;
            line-height: 50px;
            letter-spacing: 10px;
            /*字体倾斜*/
            font-style: italic;
            /*鼠标图标变为小手图标*/
            cursor: pointer;
        }

        a {
            text-decoration: none;
            color: #baff4d;
        }

        a:hover {
            text-decoration: underline;
        }

        input {
            height: 30px;
            /*设置圆角框*/
            border-radius: 5px;
            border: 1px solid grey;
        }

        button {
            height: 30px;
            background-color: #baff4d;
            border: 1px solid grey;
            border-radius: 5px;
        }
    </style>
</head>
<body onload="createCode()">          <!--onload当页面或者图像加载完之后立即执行-->
<div class="code" onclick="createCode()"></div>
<a href="#" onclick="createCode()">看不清换一张</a><br>
<input type="text" placeholder="请输入验证码">
<button onclick="checkCode()">确定</button>

<script>
    // 生成验证码的函数
    var code;
    function createCode() {
        code = "";            //验证码的初始值
        var codeLength = 4;   //验证码的长度
        // 验证码的组成成分
        var codeChars = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f',
            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
            'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
        for(var i=0;i<codeLength;i++){
            // 获取的四个随机数:下标
            var charNum = Math.floor(Math.random()*62);
            // 验证码
            code += codeChars[charNum];
        }
        document.getElementsByClassName("code")[0].innerText = code;
    }
    // 验证验证码的函数
    function checkCode() {
        // 获取输入的值
        var inputCode = document.getElementsByTagName("input")[0].value;
        // 判断验证码是否输入正确
        if (inputCode.length<=0){
            alert("请输入验证码!");
        }else if(inputCode.toUpperCase() != code.toUpperCase()){
            alert("验证码输入有误!");
            // 更新验证码
            createCode();
            // 清空输入框
            document.getElementsByTagName("input")[0].value = "";
        }else{
            alert("祝贺你:没有错误哦!")
        }
    }

</script>

</body>
</html>
发布了65 篇原创文章 · 获赞 50 · 访问量 3571

猜你喜欢

转载自blog.csdn.net/qq_44907926/article/details/105011252