js实现数字时钟

    看过别人的思路,自己也写了一个。原理就是准备10张图,图片名分别和图上的数字对应,时间的格式是xx:xx:xx,分别有六个位置的图片需要动态修改crs属性,每个位置上的数字是n(具体由当前时间决定),这个位置上的图片即为n.gif,就这样。

请先查看Demo

然后是结构:

View Code
1 <p>
2 当前时间为:
3 <span id="clock">
4 <img class="num" src="images/0.gif" />
5 <img class="num" src="images/0.gif" />
6 <img src="images/colon.gif" />
7 <img class="num" src="images/0.gif" />
8 <img class="num" src="images/0.gif" />
9 <img src="images/colon.gif" />
10 <img class="num" src="images/0.gif" />
11 <img class="num" src="images/0.gif" />
12 </span>
13 </p>

最后是js:

function Clock(id, className) {
	this.id = id;
	this.className = className;
	this.imgs = getByClass(this.className, $(this.id));
	Clock.clocks.push(this);
	for(var i=0; i<Clock.clocks.length; i++) {
		Clock.clocks[i].go();
	}
	var _this = this;
	setInterval(function() {
		_this.go();
	}, 1000);
}

Clock.clocks = [];
Clock.preZero = function(n) {//前导0
	return ('0'.repeat(1) + n).slice(-2);
}

Clock.prototype = {
	setTime: function(h, m, s) {
		this.setImg(Clock.preZero(h) + Clock.preZero(m) + Clock.preZero(s));//把时间推入一个字符串中
	},
	setImg: function(s) {
		for(var i=0; i<this.imgs.length; i++) {
			this.imgs[i].src = 'images/' + s[i] + '.gif';//每张图片的名字就是它所表示的时间part的数字
		};
	},
	go: function() {
		var date = new Date();
		this.setTime(date.getHours(), date.getMinutes(), date.getSeconds());
	}
}

window.onload = function() {
	var newClock1 = new Clock('clock', 'num');
}
这里默认的那些方法就不贴出来了,你知道的^_^!

posted @ 2011-03-10 23:48  chemdemo  阅读(1957)  评论(0编辑  收藏  举报