倒计时不起作用

时间:2015-03-10 21:43:48

标签: javascript html css timer countdown

我有一个脚本,其中我试图进行倒计时,倒计时30天,然后重置为30天并重新开始。但我的问题是,当我在浏览器中打开它(safari)时,页面是空白的,没有任何内容,但是如果我删除了我用来重置倒计时的功能,它可以工作,但我需要它重置。

if (seconds_left <= 0){
    target_date = target_date + 30 days;
}

完整代码:

 <!DOCTYPE html>


<html>

<head>
</head>

<body>

    <span id="countdown"></span>

    <script LANGUAGE="Javascript">

    var target_date = new Date("Apr 9, 2015").getTime();

    var days, hours, minutes, seconds;

    var countdown = document.getElementById("countdown");


    if (seconds_left <= 0){
            target_date = target_date + 30 days;
        }

    setInterval(function () {

    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;

    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;

    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;

    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);

    countdown.innerHTML = days + "d, " + hours + "h, "
    + minutes + "m, " + seconds + "s";  

    }, 1000);

</script>

</body>

</html>

1 个答案:

答案 0 :(得分:0)

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <span id="countdown"></span>

        <script type="text/javascript">

        var target_date = new Date("Apr 9, 2015").getTime();

        var days, hours, minutes, seconds;

        var countdown = document.getElementById("countdown");

        setInterval(function () {

            var current_date = new Date().getTime();
            var seconds_left = (target_date - current_date) / 1000;

            //the following two lines are moved inside the function
            if (seconds_left <= 0)
            {
                target_date = target_date + 30; //just 30 would suffice to add 30 days
                seconds_left = (target_date - current_date) / 1000; //then update the seconds_left to continue
            }

            days = parseInt(seconds_left / 86400);
            seconds_left = seconds_left % 86400;

            hours = parseInt(seconds_left / 3600);
            seconds_left = seconds_left % 3600;

            minutes = parseInt(seconds_left / 60);
            seconds = parseInt(seconds_left % 60);

            countdown.innerHTML = days + "d, " + hours + "h, "
            + minutes + "m, " + seconds + "s";  

        }, 1000);
    </script>
    </body>
</html>