计时器Javascript

时间:2012-07-12 17:13:51

标签: javascript

这在IE中不起作用。永远 - 00:00:00 适用于Chrome,Firefox。 为什么? 我该如何解决?

function timer()
{
    var now = new Date();
    var enddate = new Date("07,12,2012,23:00:00");
    var totalRemains = (enddate.getTime()-now.getTime());
    if (totalRemains>1)
    {
        var RemainsSec=(parseInt(totalRemains/1000));
        var RemainsFullDays=(parseInt(RemainsSec/(24*60*60)));
        var secInLastDay=RemainsSec-RemainsFullDays*24*3600;
        var RemainsFullHours=(parseInt(secInLastDay/3600));
        if (RemainsFullHours<10){RemainsFullHours="0"+RemainsFullHours};
        var secInLastHour=secInLastDay-RemainsFullHours*3600;
        var RemainsMinutes=(parseInt(secInLastHour/60));
        if (RemainsMinutes<10){RemainsMinutes="0"+RemainsMinutes};
        var lastSec=secInLastHour-RemainsMinutes*60;
        if (lastSec<10){lastSec="0"+lastSec};
        var mcend = Date.parse("Jan 1, 2009, 00:00:00");
        var mcnow = now.getTime();
        var mc = ((mcend-mcnow)/10).toFixed(0).substr(8);
        document.getElementById('timer').innerHTML = '<p class="timeline">TIME LEFT: '+ RemainsFullHours+":"+RemainsMinutes+":"+lastSec+'</p>';
        setTimeout("timer()",10);
    } 
    else {document.getElementById("timer").innerHTML = '<p class="timeline">TIME LEFT: 00:00:00</p>';}
}

<body onload="timer();">

你能帮我吗?

1 个答案:

答案 0 :(得分:4)

问题出在这一行:

var enddate = new Date("07,12,2012,23:00:00");

这不是日期格式。 Firefox正在英勇地理解它,不要指望Internet Explorer会帮助你解决这个问题,IE是无情的,他一个人走路。

Date对象构造函数有几个参数:

  

新日期()
      新日期(毫秒)
      新日期(dateString)
      新日期(年,月,日[,小时,分钟,秒,毫秒])

使用dateString选项时,您的日期字符串必须符合the RFC 2822 specification;如果您使用支持的格式,它可以工作:

var enddate = new Date("July 12, 2012 23:00:00");

AND,永远不会,永远不会将字符串传递给setTimeout,而是传递一个函数引用:

setTimeout(timer,10);

在此处试试:http://jsfiddle.net/bVCMe/

<强>文档