2012-09-17 29 views
0

我有倒計時腳本,但我有2個問題。 1.我的倒計時從未達到0並停止,因此我得到一個連續的負數。 2.計數器只顯示在Chrome中,而不是Firefox或Internet Explorer。我如何修復這兩個isses?倒計時從來沒有達到0,並給出負值

var sec, min, hr, day, timer, expireDate; 

sec = 1000; 
min = 60 * 1000; 
hr = 60 * 60 * 1000; 
day = 24 * 60 * 60 * 1000; 
timer; 
expireDate = new Date('Mon Sep 17 2012 14:26:00 GMT-0700'); 

timer = setInterval(function() { 
    var currentDate, countdown, days, hours, minutes, seconds; 
    currentDate = new Date(); 
    countdown = expireDate - currentDate; 
    if (countdown === 0) { 
     window.clearInterval(timer); 
     document.getElementById('countdown').innerHTML = 'EXPIRED!'; 
    } 

    days = Math.floor(countdown/day); 
    hours = Math.floor((countdown % day)/hr); 
    minutes = Math.floor((countdown % hr)/min); 
    seconds = Math.floor((countdown % min)/sec); 
    console.log(countdown); 
    document.getElementById('countdown').innerHTML = days + " " + hours + " " + minutes + " " + seconds; 
}, 1000);​ 

回答

1

如前所述別人,你應該使用< 0

此外,一旦您的過期條件得到滿足,您立即覆蓋EXPIRED!標籤,所以你永遠不會看到它。您需要將if後面的代碼移動到else或者僅在if內返回。

if (countdown <= 0) { 
    window.clearInterval(timer); 
    document.getElementById('countdown').innerHTML = 'EXPIRED!'; 
} else { 
    days = Math.floor(countdown/day); 
    hours = Math.floor((countdown % day)/hr); 
    minutes = Math.floor((countdown % hr)/min); 
    seconds = Math.floor((countdown % min)/sec); 
    console.log(countdown); 
    document.getElementById('countdown').innerHTML = days + " " + hours + " " + minutes + " " + seconds; 
} 

最後,它不會在IE中工作的原因可能是console.log。如果您當時沒有打開控制檯,IE將會失敗。只需刪除console.log行,這在IE中工作得很好。

+0

太棒了!謝謝。 –

2

在這兩條線:

currentDate = new Date(); 
countdown = expireDate - currentDate; 

你得到的當前時間和預計時間到毫秒的區別!

如果它沒有達到正確的值,它會直接通過它。

===測試更改爲<=

0

你是比較次到毫秒!你必須是驚人的幸運,使這項工作:

currentDate = new Date(); 
countdown = expireDate - currentDate; 

嘗試:

if (countdown < 0) {