完成后重定向的倒计时器

时间:2013-05-07 13:02:07

标签: javascript redirect countdown

我一直在尝试为特定时间和日期(即9am GMT June 17th 2013)的倒数计时器找到一个脚本(最好是JavaScript)。当倒计时完成时(即在9am GMT on June 17th之后),我希望该网站开始自动重定向到另一个页面。

1 个答案:

答案 0 :(得分:0)

我实际上写了一个简单的倒计时脚本,用于我们与同事进行局域网聚会时: - )

我没有花时间把它变成一个jQuery插件,它有一个奇怪的结构,但是它可以工作,你可以根据自己的需要进行修改。

http://jsfiddle.net/Y6n9W/

(function($, undefined) {
    countdown = function(settings) {
        var _this = this,
            defaults = {
                end: '30.09.2012 09:00'
            }, rDate = /(\d+).(\d+).(\d+) (\d+):(\d+)/;

        _this.settings = $.extend(defaults, settings);

        var matches = _this.settings.end.match(rDate);

        _this.endDate = new Date(matches[3], matches[2] - 1, matches[1], matches[4], matches[5], 0, 0);

        _this.nDays = $('<span />').addClass('countdown days').html('0');
        _this.nHours = $('<span />').addClass('countdown hours').html('0');
        _this.nMinutes = $('<span />').addClass('countdown minutes').html('0');
        _this.nSeconds = $('<span />').addClass('countdown seconds').html('0');

        _this.settings.element.append(
            $('<span />').append(
                _this.nDays,
                ' Days'
            ),
            $('<span />').append(
                _this.nHours,
                ' Hours'
            ),
            $('<span />').append(
                _this.nMinutes,
                ' Minutes'
            ),
            $('<span />').append(
                _this.nSeconds,
                ' Seconds'
            )
        );

        countdownMethods.start.call(_this);

        return _this;
    };

    var countdownMethods = {
        start: function() {
            var _this = this,
                interval = 0;

            var updateTime = function() {
                var now = new Date(),
                    diff = Math.round((_this.endDate - now) / 1000);

                if(diff < 0) {
                    diff = 0;
                    clearInterval(interval);
                    window.location.href = 'newurl..';
                }

                var days = Math.floor(diff/86400);

                diff -= days * 86400;

                var hours = Math.floor(diff/3600);
                diff -= hours * 3600;

                var minutes = Math.floor(diff/60);
                diff -= minutes * 60;

                _this.nDays.html(days);
                _this.nHours.html(hours);
                _this.nMinutes.html(minutes);
                _this.nSeconds.html(diff);
            };

            updateTime();

            interval = setInterval(function() {
                updateTime();
            }, 1000);
        }
    };
})(jQuery);

你这样使用它:

$(function() {
    var counter = countdown({
        end: '08.05.2013 15:15',
        element: $('div')
    });
});