前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-3.4.1.js"></script>
<!-- 引入 layui.css -->
<link rel="stylesheet" href="layui/css/layui.css">
<!-- 引入 layui.js -->
<script src="layui/layui.js"></script>
</head>
<body>
<form class="layui-form" action="" onsubmit="return false">
<div class="layui-form-item">
<label class="layui-form-label">验证码:</label>
<div class="layui-input-inline">
<input type="text" name="code" required lay-verify="required" placeholder="请输入验证码" autocomplete="off" class="layui-input">
</div>
<div>
<img src="/LiuYanCodeServlet" id="yzm" style="height: 37px;80px">
<span id="msg">点击图片刷新</span>
</div>
</div>
</form>
<script >
var num = 0;
var wait = 60;
var pass = true;
//验证码 点击刷新 每三次后锁定60秒
$(function () {
var fun = $("#yzm").click(function(){
var time = new Date().getTime();
//选中img标签,将属性设置为验证码路径。一定要加随机数,否则会认为请求相同不做处理
//获取刷新次数
if (num < 3) {
$(this).attr("src","LiuYanCodeServlet?"+time);
$("#msg").text("点击图片刷新").css("color","black");
} else {
setTimeout(fun,60000); //每次点击60秒后才能再次点击
$("#msg").text("请"+wait+"秒后在刷新").css("color","red");
pass = false;
}
console.log('num',num);
++num;
});
setInterval(function(){
console.log('wait',wait);
console.log('pass',pass);
//锁定 倒计时
if (pass == false) {
if(wait==0){
//计时结束,数据恢复
wait = 60;
num = 0;
pass = true;
$("#msg").text("点击图片刷新").css("color","black");
}else{
$("#msg").text("请"+wait+"秒后在刷新").css("color","red");
wait--;
}
}
}, 1000);
});
</script>
</body>
</html>