本周主要通过一些小练习复习巩固JS
相关知识
参考视频
现总结随机生成四位数字、字母验证码(区分大小写)页面如下
基础布局代码如下
<div class="v_code">
<div class="code_show">
<span class="code" id="checkCode"></span>
<a id="linkbt">看不清换一张</a>
</div>
<div class="input_code">
<label for="inputCode">请输入验证码:</label>
<input type="text" id="inputCode" />
<span id="text_show"></span>
</div>
<input id="Button1" type="button" value="点击跳转" />
</div>
<style>
.v_code {
width: 600px;
margin: 0 auto;
}
.v_code>input {
width: 60px;
height: 36px;
margin-top: 10px;
}
.code_show {
overflow: hidden;
}
.code_show span {
display: block;
float: left;
margin-bottom: 10px;
}
.code_show a {
display: block;
float: left;
margin-top: 10px;
margin-left: 10px;
}
.code {
font-style: italic;
background-color: #f5f5f5;
color: blue;
font-size: 30px;
letter-spacing: 3px;
font-weight: bolder;
float: left;
cursor: pointer;
padding: 0 5px;
text-align: center;
}
#inputCode {
width: 100px;
height: 30px;
}
a {
text-decoration: none;
font-size: 12px;
color: #288bc4;
cursor: pointer;
}
a:hover {
text-decoration: underline;
}
.form {
width: 300px;
height: 300px;
background-color: #eee;
}
#Button1 {
width: 100px;
text-align: center;
position: relative;
left: 50px;
}
</style>
生成函数getPassword()
- 通过一个字符串整合生成的验证码
- 通过随机生成的
flag
的奇偶来决定是数字还是字母以及大小写
flag = parseInt(Math.random() * 10) % 2
- 生成随机的数字
str += parseInt(Math.random() * 10)
- 生成随机的小写字母
str += String.fromCharCode(
Math.floor(Math.random() * 26) + "a".charCodeAt(0)
)
- 生成随机的大写字母
str += String.fromCharCode(
Math.floor(Math.random() * 26) + "A".charCodeAt(0)
)
- 将生成的验证码
return
功能实现:
- 页面打开时生成验证码
- 点击“看不清”时生成验证码
change.addEventListener('click', function () {
check.innerText = getPassword()
})
- 输入错误时弹出提示
but.addEventListener('click', function () {
var password = check.innerText;
var input = document.querySelector("#inputCode").value
if (password != input) {
alert('验证码错误!')
check.innerText = getPassword()
document.querySelector("#inputCode").value = ''
}
})
完整代码如下:
<script>
var but = document.querySelector('#Button1')
var change = document.querySelector('#linkbt')
var check = document.querySelector('#checkCode')
function getPassword() {
var str = ''
var flag
for (var i = 0; i < 4; i++) {
flag = parseInt(Math.random() * 10) % 2
if (!flag)
str += parseInt(Math.random() * 10)
else {
flag = parseInt(Math.random() * 10) % 2
if (flag) {
str += String.fromCharCode(
// 97
Math.floor(Math.random() * 26) + "a".charCodeAt(0)
)
}
else {
str += String.fromCharCode(
Math.floor(Math.random() * 26) + "A".charCodeAt(0)
)
}
}
}
return (str)
}
window.onload = function () {
var res = getPassword()
check.innerText = res
change.addEventListener('click', function () {
check.innerText = getPassword()
})
but.addEventListener('click', function () {
var password = check.innerText;
var input = document.querySelector("#inputCode").value
if (password != input) {
alert('验证码错误!')
check.innerText = getPassword()
document.querySelector("#inputCode").value = ''
}
})
}
</script>