JavaScript Math.floor()、Math.random()实现验证码效果

效果图:
这里写图片描述

HTML代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <script src="js/test.js"></script>
</head>
<body>

<div>
    <input id="t1" type="text" placeholder="验证码"/>
    <span id="discode"></span>
    <input type="button" value="换一个" onclick="createCode()">
    <button type="button" onclick="but()">提交验证</button>
</div>

</body>
</html>

JavaScript1代码:

var code; //在全局 定义验证码
function createCode() { //创建验证码函数
    code = "";
    var codeLength = 4;//验证码的长度
    var selectChar = [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'];//所有候选组成验证码的字符,当然也可以用中文的
    for (var i = 0; i < codeLength; i++) {
        var charIndex = Math.floor(Math.random() * 36);
        // Math.random()会产生一个[0,1)的数
        // Math.random()*36会产生一个[0,36)的数,注意其中包含了小数
        // Math.floor(x) 方法返回小于等于x的最大整数。
        // Math.floor(Math.random()*36)会对由上面的语句产生的数值进行向下取整
        // 例如产生的数为5.5,则math.floor(5.5)=5
        // 最后把这个数赋值给变量i

        code += selectChar[charIndex];
    }
// 设置验证码的显示样式,并显示
    document.getElementById("discode").style.fontFamily = "Fixedsys"; //设置字体
    document.getElementById("discode").style.letterSpacing = "5px"; //字体间距
    document.getElementById("discode").style.color = "#b0000b"; //字体颜色
    document.getElementById("discode").innerHTML = code.toUpperCase(); // 显示
}

function but() {//验证验证码输入是否正确
    var val1 = document.getElementById("t1").value.toUpperCase();
    var val2 = code.toUpperCase();
    if (val1 != val2) {
        alert("验证码错误!");
        document.getElementById('t1').value = "";
    }
    else {
        alert("提交成功");
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37273490/article/details/80588401
今日推荐