随着网络的发达,总会有人恶意注册网站,而使用输入验证码功能可以有效的阻止这一类现象的发生。不管pc端还是手机端我们都会发现在注册、登录、实名认证等功能都会用到验证码功能。
使用验证码功能的步骤往往是: 获取验证码(60秒倒计时)----输入验证码,下面我们就来实现获取验证码时60秒倒计时的功能。
首先我们先看看uniapp如何实现
效果:
点击 “获取倒计时”后
直接上代码:
<template>
<view>
<button class="code" @click="getcode" v-show="numShow">获取验证码</button>
<button class="code" v-show="!numShow">{{num}}s</button>
</view>
</template>
<script>
export default {
data() {
return {
numShow: true,
num: 60 //倒计时初始值
}
},
methods: {
// 验证码倒计时
getcode() {
this.numShow = false
var interval = setInterval(() => {
--this.num
}, 1000)
setTimeout(() => {
clearInterval(interval)
this.numShow = true
// 再将num设为初始值,否则第二次点击时,倒计时从0开始
this.num = 60
}, 60000)
}
}
}
</script>
<style>
</style>
通过定时器就可以实现了,下面看看原生html的写法
效果:
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.code {
width: 150px;
height: 150px;
line-height: 150px;
text-align: center;
font-size: 20px;
background: #03a9f4;
color: #fff;
}
.getCode1 {
display: block;
}
.getCode2 {
display: none;
}
</style>
</head>
<body>
<div>
<div class="code getCode1">获取验证码</div>
<div class="code getCode2">60s后获取</div>
</div>
</body>
<script src="./js/jquery-3.1.1.min.js"></script>
<script>
$(".getCode1").click(function() {
$(".getCode1").css("display", "none");
$(".getCode2").css("display", "block");
var s = 60;
var timer = setInterval(function() {
s--;
var name = s + "s后获取";
$(".getCode2").html(name);
if (s < 1) {
s = 60;
$(".getCode1").css("display", "block");
$(".getCode2").css("display", "none");
$(".getCode2").html("获取验证码");
clearInterval(timer);
}
}, 1000);
});
</script>
</html>
以上就是在uniapp和原生html页面实现获取验证码倒计时功能了,都是通过计时器完成,只是写法不一样而已!