倒计时(Jquery插件)

/**
 * 倒计时(Jquery插件)
 *
 * @author Johnson
 * @version Tuesday Novermber 22th, 2011
 
 * @example 
 * 	var now = "2011-11-22 13:45:11";
 *	var tdate = "2012-12-21 12:21:12";
 *	$("#counter").countdown(now, tdate, function(){});
 *  日期格式还可为以下格式:
 *	var now = new Date(2011, 11, 22, 13, 45, 11);
 *	var now = Date.parse("2011-11-22 13:45:11");
 *
 * @param now 当前时间
 * @param tdate 目标时间
 * @param fn 倒数完成回调函数
 **/
$.fn.countdown = function(now, tdate, fn){
	var obj = $(this);
	var c = 0;
	var t = null;
	function init(){
		var ntime = getTime(now);
		var ttime = getTime(tdate);
		var time = ttime - ntime;		
		counter(time, fn);
		t = setInterval(function(){
			counter(time, fn);
		}, 1000);
	};
	function getTime(date) {
		var time = 0;
		switch(typeof(date)) {
		case "object":
			date.setMonth(date.getMonth() - 1);
			time = date.getTime();
			break;
		case "string":
			time = Date.parse(date.replace(/\-/ig, '/'));
			break;
		case "number":
			time = date;
			break;
		}
		return time;
	};
	function counter(time, fn) {
		var html = null;
		var mills = time - c;
		var ndate = new Date(mills - 8 * 60 * 60 * 1000);
		var stop = false;
		if (mills < 1000) {
			html = getOutputHtml(0, 0, 0, 0);
			stop = true;
		} else {
			var day = Math.floor(mills / (1000 * 60 * 60 * 24));
			html = getOutputHtml(day, ndate.getHours(), ndate.getMinutes(), ndate.getSeconds());
		}
		obj.html(html);
		if (stop) {
			clearInterval(t);
			if (fn) {
				fn();
			}
		} else {
			c += 1000;
		}
	}
	function getOutputHtml(day, hh, mi, ss) {
		var html = "";
		html += '<span>' + day + '</span>天';
		html += '<span>' + (hh < 10 ? '0' + hh : hh) + '</span>时';
		html += '<span>' + (mi < 10 ? '0' + mi : mi) + '</span>分';
		html += '<span>' + (ss < 10 ? '0' + ss : ss) + '</span>秒';
		return html;
	}
	init();
};

你可能感兴趣的:(html,Date,object,String,function,jquery插件)