JS——实现短信验证码的倒计时功能(没有验证码,只有倒计时)

1、功能描述

  当用户想要获取验证码时,就点击 免费获取验证码 ,然后开始倒计时,倒计时期间按钮文字为剩余时间x秒,且不可按状态,倒计时结束后,按钮更改为点击重新发送。

2、分析

  必须用到定时器。按钮点击后,在定时器内做出判断。倒计时60秒,到0结束。

3、代码实现:

  重点介绍:定时器在进行下一次倒计时之前,一定要清除一下,这样的话保证下一次定时器倒计时是正常的。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            *{margin: 0;padding: 0;}
            .send{
                width:250px;
                margin:0 auto;
            }
            .send input{
                display: block;
                width:200px;
                font:400 16px/30px "微软雅黑";
                outline: none;
                border: none;
            }
            .send button{
                height:30px;
                border: none;
                outline: none;
                font:400 16px/30px "微软雅黑";
                text-align: center;
            }
        </style>
        <script type="text/javascript">
            window.onload=function(){
                var button=document.getElementsByTagName("button")[0];
                button.innerText="免费获取验证码";
                var timer=null;
                button.onclick=function(){
                    clearInterval(timer);//这句话至关重要
                    var time=6;
                    var that=this;//习惯
                    timer=setInterval(function(){
                        console.log(time);
                        if(time<=0){
                            that.innerText="";
                            that.innerText="点击重新发送";
                            that.disabled=false;
                            
                        }else {
                            that.disabled=true;
                            that.innerText="";
                            that.innerText="剩余时间"+(time)+"";
                            time--;
                        }
                    },1000);
                }
            }
        </script>
    </head>
    <body>
        <div id="send">
            <input type="text" name="in" id="in" value="" /><button></button>
        </div>
    </body>
</html>
原文地址:https://www.cnblogs.com/sylz/p/5747937.html