js生成验证码

使用面向对象编程实现了一个生成验证码的功能:
verificationCode.js代码:

function Verification(options){
    
    
    this.height = options.height || 40  //默认值
    this.width = options.width  || 100  //默认值
    this.el = options.el
    this.ele = document.querySelector(this.el)

    this.init()
}

Verification.prototype.init = function(){
    
    
    this.setStyle()
    this.getCode()
    this.myClick()
}

Verification.prototype.setStyle = function(){
    
    
    this.ele.style.width = this.width + 'px'
    this.ele.style.height = this.height + 'px'
    this.ele.style.backgroundColor = '#ccc'
    this.ele.style.lineHeight = this.height + 'px'
    this.ele.style.textAlign = 'center'
    this.ele.style.color = 'blue'
    this.ele.style.fontSize = '26px'
}

Verification.prototype.getCode = function(){
    
    
    const codeArr = [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']

    let codeStr = ''
    let len = codeArr.length - 1

    for(let i=0; i<6; i++){
    
    
        // 这里为什么要*codeArr.length-1呢?因为Math.random()生成[0, 1]之间的数,如果*codeArr.length的话,会出现codeArr[codeArr.length]
        let k = Math.round(Math.random()*len)
        // Math.round:四舍五入
        codeStr += codeArr[k]
    }
    this.ele.innerText = codeStr
}

Verification.prototype.myClick = function(){
    
    
    const that = this
    this.ele.addEventListener('click', function(){
    
    
        that.getCode()
    })
}

index.html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>验证码生成</title>
    <script src="./index.js"></script>
</head>
<body>
    <div id="verification-code" onselectstart="return false;"></div>
    <script>
        const verfication = new Verification({
      
      
            el: '#verification-code',
            width: 200,
            height: 80
        })
    </script>
</body>
</html>

我觉得还有一些需要改进的地方(但是我不知道怎么改):

1. js代码里有一个方法:setStyle用来设置验证码dom元素的样式,我是一个个设置的,可是有好多样式属性,这样好麻烦。我有想过换成设置class属性,那么就需要额外引入一个css文件,用到项目里,如果页面其它dom不小心使用了这个css文件里的样式又是个麻烦。

2. 用来生成验证码的代码函数:getCode(),设定了一个数组,然后结合Math.random()来随机生成验证码。总感觉这样有点麻烦,但是不知道怎么改?

猜你喜欢

转载自blog.csdn.net/qq_45465526/article/details/121621403
今日推荐