2016-04-03 55 views
0

我有一個倒數計時器來隱藏div,然後顯示另一個div。我已經很好地完成了這一點,但我想將秒轉換成分鐘和小時。將倒計時秒數轉換爲小時

我該怎麼做?

預先感謝任何人回答我的問題...

這是我的代碼:

var countDown = 9000; 
 
var i = setInterval(function() { 
 
    
 
    var b1 = document.getElementById('box1'); 
 
    var b2 = document.getElementById('box2'); 
 
    
 
    
 
    if(countDown === 1) { 
 
    if(b1['style'].display == 'none') { 
 
     b1['style'].display = 'block'; 
 
     b2['style'].display = 'none'; 
 
    } else { 
 
     b1['style'].display = 'none'; 
 
     b2['style'].display = 'block'; 
 
    } 
 
    clearInterval(i); 
 
    } 
 
    countDown--; 
 
    b1.innerHTML = countDown; 
 

 
}, 1000);
<!DOCTYPE html> 
 
<html> 
 

 
    <head> 
 
    <link rel="stylesheet" href="style.css"> 
 
    <script src="script.js"></script> 
 
    </head> 
 

 
    <body> 
 
    <div id="box1">9000</div> 
 

 
    <div style="display:none" id="box2">div2</div> 
 
    
 
    </body> 
 

 
</html>

+0

我想顯示的倒計時結果就像hh:mm:ss而不是9000秒...... –

回答

1

例子:https://jsfiddle.net/306qtxot/4/

你可以使用這個jQuery :

var countDown = 9000; 
var i = setInterval(function() { 

    var b1 = document.getElementById('box1'); 
    var b2 = document.getElementById('box2'); 


    if(countDown === 1) { 
    if(b1['style'].display == 'none') { 
     b1['style'].display = 'block'; 
     b2['style'].display = 'none'; 
    } else { 
     b1['style'].display = 'none'; 
     b2['style'].display = 'block'; 
    } 
    clearInterval(i); 
    } 
    countDown--; 

    //This section convert "seconds" to hour And minute And second 
    var hour=Math.floor(countDown/3600); 
    var min=Math.floor(countDown%3600/60); 
    var sec=Math.floor(countDown%3600%60); 

    //Format : hh:mm:ss 
    b1.innerHTML = (hour=hour<10?"0"+hour:hour) + " : " + (min=min<10?"0"+min:min) + " : " + (sec=sec<10?"0"+sec:sec); 

}, 1000); 
+1

只需在最後一行之前添加這些行即可。 'if(hour <10)hour =「0」+ hour; (min <10)min =「0」+ min; if(sec <10)sec =「0」+ sec;' – qmaruf

+0

@qmaruf這是最好的解決方案 –

+0

非常感謝。它工作得很好。 真誠感謝。 –