美文网首页
简单实现验证码倒计时功能

简单实现验证码倒计时功能

作者: zsanpang | 来源:发表于2019-05-17 19:03 被阅读0次

根据业务开发需求延伸做的小demo

  • html代码块
   <div id="app">
        <input type="text" v-model="mobile" placeholder="输入手机号">
        <button :class="{gray:waitTimer>0}" @click='test'>{{ confirmText }}</button>
   </div>

-css代码块

        #app {
            display: flex;
        }

        input {
            font-size: 16px;
            padding: 4px;
            -webkit-tap-highlight-color: transparent;
            outline-style: none;
            list-style: none;
            outline: none;
            border-radius: 4px;
            border: 1px solid #0000ff;
        }

        button {
            max-width: 100px;
            height: 40px;
            font-size: 13px;
            color: white;
            background: #0000ff;
            border-radius: 4px;
            text-align: center;
            line-height:40px;
            outline: none;
            border: none;
            cursor: pointer;
            margin-left: 4px;
        }

        button.gray {
            background: #c8c8c8;
        }
  • js代码块
    <script src="./js/vue.min.2.5.13.js"></script>
    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                mobile: '',
                waitTimer: false,
                confirmText:'获取验证码'
            },
            methods: {
                test: function () {
                    if (this.waitTimer > 0) {
                        return false;
                    }
                    if (!this.mobile) {
                        alert('手机号不能为空');
                        return false;
                    }
                    if (!/^1[3|4|5|6|7|8]\d{9}$/.test(this.mobile)) {
                        alert('手机号格式不正确');
                        return false;
                    }

                    this.waitTimer = 59;
                    let that = this;
                    let timerInterval = setInterval(function () {
                        if (that.waitTimer > 0) {
                            that.confirmText = that.waitTimer + 's后获取';
                            that.waitTimer--;
                        } else if (that.waitTimer === 0) {
                            return that.confirmText = '重新获取';
                        } else if (that.waitTimer === false) {
                            return that.confirmText = '获取验证码';
                        } else {
                            clearInterval(timerInterval);
                        }
                    }, 1000);
                    // 代码逻辑
                },
            }
        })
    </script>
  • 最终实现如下图

最后还需要提醒大家一点,本篇文章中的例子仅供参考学习,切误将本篇文章中的代码直接使用在正式项目当中。希望以上代码对大家有所帮助。

相关文章

网友评论

      本文标题:简单实现验证码倒计时功能

      本文链接:https://www.haomeiwen.com/subject/ylqoaqtx.html