我有一个倒计时脚本,但是有两个问题。 1.我的倒数永远不会达到0并停止,所以我得到一个连续的负数。 2.计数器仅在Chrome中显示,而在Firefox或Internet Explorer中不显示。如何解决这两个问题?

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);​

最佳答案

如其他人所述,您应该使用< 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中正常运行。

关于javascript - 倒数永远不会达到0并给出负值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12467351/

10-11 16:19