1. 程式人生 > >JS 獲取驗證碼 倒計時

JS 獲取驗證碼 倒計時

ner timer set 空間 cursor padding ble on() ==

setInterval 一個定時器搞定


<style>
button{
    background: #45BCF9;
    color: #fff;
    padding: 4px 10px;
    border: none;
    outline: none;
    cursor: pointer;
}
button:hover{
    background: #00a8fe;
}
button.disabled{
    background: #000;
    cursor: auto;
}
button.disabled:hover{
    background: #000;
}
</style>
<button type="button" onclick="fn()">獲取驗證碼</button>
<script>
function fn(){
    var oBtn = document.getElementsByTagName('button')[0];
    var time = 60;
    var timer = null;

    oBtn.innerHTML = time + '秒後重新發送';
    oBtn.setAttribute('disabled', 'disabled');   // 禁用按鈕
    oBtn.setAttribute('class', 'disabled');      // 添加class 按鈕樣式變灰

    timer = setInterval(function(){
        // 定時器到底了 兄弟們回家啦
        if(time == 1){
            clearInterval(timer);             
            oBtn.innerHTML = '獲取驗證碼';    
            oBtn.removeAttribute('disabled'); 
            oBtn.removeAttribute('class');    
        }else{
            time--;
            oBtn.innerHTML = time + '秒後重新發送';
        }
    }, 1000)
}
</script>

這邊穿梭進入演示空間

JS 獲取驗證碼 倒計時