0

我有一个简单的倒计时脚本。该代码适用于chrome,但不适用于firefox。在 Firefox 中它显示 NaN 但 chrome 显示倒计时任何想法为什么会发生这种情况?

function CountDownTimer(time, name) {
  var counter = setInterval(function(){
    var today = new Date();
    var expire = new Date(time);
    var timeRemains = expire - today;

    var days  = Math.floor(timeRemains / (1000 * 60 * 60 * 24));
    var hours = Math.floor(timeRemains / (1000 * 60 * 60));
    var mins  = Math.floor(timeRemains / (1000 * 60));
    var secs  = Math.floor(timeRemains / 1000);

    var dd = days;
    var hh = hours - days  * 24;
    var mm = mins  - hours * 60;
    var ss = secs  - mins  * 60;

    if (expire < today) {
      clearInterval(counter);
      document.getElementById(name).innerHTML = '<span class="expire">expire!</span>';
      return;
    } else {
         if (dd < 10) {
             dd = "0" + dd;
         }
         if (hh < 10) {
             hh = "0" + hh;
         }
         if (mm < 10) {
             mm = "0" + mm;
         }
         if (ss < 10) {
             ss = "0" + ss;
         }
         document.getElementById(name).innerHTML = dd + ' : ' + hh + ' : ' + mm + ' : ' + ss;
    }
  }, 1000 );
}


CountDownTimer("2012-07-06 19:00:00", "Time1");​
4

4 回答 4

2

更改日期格式,如下所示:

CountDownTimer("June 7, 2012 19:00:00", "Time1");​
于 2012-07-07T02:06:51.027 回答
2

Date() 函数似乎不适用于所有浏览器。尝试在其上使用 setUTC 函数,如下所示:

today.setUTCFullYear(2012);
today.setUTCHours(19, 0, 0, 0);

更新: Date() 构造函数在所有浏览器上都很好,只是在使用“不正确”字符串时不行。试试这个:

var today = new Date(2012,6,7,19,0,0)
于 2012-07-07T02:09:43.647 回答
0

NaN代表不是一个数字。

如果 Leo 的建议没有帮助,可能值得添加一些零星console.log()的 ' 来找出问题所在。

于 2012-07-07T02:10:36.603 回答
0

问题在于新的 Date() 格式,该格式在浏览器中不一致。

Problem with date formats in JavaScript with different browsers.

You can likely make it work by converting the - chars to /. Cameron's answer should provide good cross-browser behaviour, otherwise consider using a 3rd party library such as moment.js

https://stackoverflow.com/questions/802861/javascript-date-manipulation-library

于 2012-07-07T02:30:45.193 回答