零碎笔记:实现点击验证码开始倒计时功能

实现点击验证码开始倒计时

在项目中涉及到短信验证功能时必不可少的是发送验证码的点击后倒计时效果,本次记录使用jquery和vue两种方式的实现:

使用jquery实现
  • HTML部分
<form>
        <input type="number" class="iphone" name="iphone" maxlength="11" placeholder="请输入11位手机号" id="codeMobile" />
        <input type="number" class="code" name="code" maxlength="4" placeholder="请输入4位验证码" id="code" />
        <input type="button" id="btnSend" class="btn-code" value="发送验证码" disabled="disabled" />             
        <input type="button" class="submit" value="登录" id="subloginCode" />
</form>
  • js部分
//封装倒计时函数
        var wait = 60;
        function time(o) {
            if(wait == 0) {
                $(o).removeAttr("disabled").val("重新获取").css({
                    'background': '#d0e8d2',
                    'color': '#8aa78a',
                    'box-shadow': '0 0px 3px 0px #a5d4ad'
                });
                wait = 60;
            } else {
                $(o).attr("disabled", 'disabled').val('剩余' + wait + 's').css({
                    'background': '#eee',
                    'color': '#888',
                    'box-shadow': '0 0 0 0 #fff'
                });
                wait--;
                setTimeout(function() {
                    time(o);
                }, 1000);
            }
        }
//点击发送验证码按钮
var btnSend = $('#btnSend');
btnSend.on('click', function() {
    ...
    //如果不嵌套发送验证的ajax可直接使用time(this)
    time(btnSend)
    ... 
})
使用vue实现
  • HTM部分
 <input type="button" id="btnSend" class="btn-code" value="发送验证码" disabled="disabled" v-model='btnSend' @click="sendCode" ref="btnSend" />
  • js部分(在methods中定义sendcode方法)
   //data中定义timer,count
    count: '', //按钮上显示的秒值
    timer: null 

   //methods中定义发送验证码方法
    sendCode() {
         ...
         this.pupUp('发送成功')
         const num = 60
         if (!this.timer) {
             this.count = num
             this.btnSend = '剩余' + this.count + '秒'
             this.timer = setInterval(() => {
                 if (this.count > 0 && this.count <= num) {
                        this.count--
                        this.btnSend = '剩余' + this.count + '秒'
                 } else {
                        this.btnSend = '发送验证码'
                        clearInterval(this.timer)
                        this.timer = null
                 }
              }, 1000)
          }

    },

记录点滴,每天进步一点点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值