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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM