使用面向对象编程实现了一个生成验证码的功能:
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>