上一篇,我们干完了脏活,休息了好一会儿,现在精神又饱满了,是时侯让我们的二进制时钟跳起来啦。
    首先我们先设定两个变量,用来保存表示0时img的颜色和表示1时img的颜色,代码如下

1var grayColor = "#f0f0f0";
2var highlightColor = "#505050";

    下面的任务就是控制各个img在什么时候变成1,什么时候变成0
    小时、分钟和秒都是由两部分组成的,一个是它的十位,一个是它的个位,十位和个位都是由4个二进制位来编码,所以每竖着的4个二进制位和一个0~9的数一一对应,因此可以抽象出一个函数,它接收两个参数,第一个是当前操作的是哪个列,第二个是当前这个列显示的数字,先看代码    
 1function liteup(col, num)
 2{
 3    var currentColor;
 4    if (num % 2 == 1)
 5    {
 6        currentColor = highlightColor;
 7    }

 8    else
 9    {
10        currentColor = grayColor;
11    }

12    eval("document.getElementById('" + col + "1').style.background='" + currentColor + "';");
13
14    if (num == 2 || num == 3 ||num == 6 || num == 7)
15    {
16        currentColor = highlightColor;
17    }

18    else
19    {
20        currentColor = grayColor;
21    }

22    eval("document.getElementById('" + col + "2').style.background='" + currentColor + "';");
23
24    if (num <= 7 && num >= 4)
25    {
26        currentColor = highlightColor;
27    }

28    else
29    {
30        currentColor = grayColor;
31    }

32    eval("document.getElementById('" + col + "4').style.background='" + currentColor + "';");
33
34    if (num >= 8)
35    {
36        currentColor = highlightColor;
37    }

38    else
39    {
40        currentColor = grayColor;
41    }

42    eval("document.getElementById('" + col + "8').style.background='" + currentColor + "';");
43    return true;
44}
    参数col接收要更新的列,参数num就是要更新的数,我们仔细看看第一个分支的逻辑:如果要更新的数不可以被二整除,说明此列的最低二进制位为1,将当前颜色设置为highlightColor,否则就设置为grayColor,然后在页面中找到id为col + "1"的img,并将其背景色设置为当前颜色。第二、三、四个分支分别控制其余的三个二进制位颜色,下面的任务就是调用该函数来做具体的显示了。
    要显示时间,首先得从系统中读到数据,javascript有一个现成的对象是管理所有时间数据的,他就是Date,实例化这个对象后可以从中读到年月日分时秒等等信息,这里我们只需要分时秒,看看代码
 1function timeit()
 2{
 3    timenow = new Date();
 4    liteup("h1", Math.floor(timenow.getHours() / 10));
 5    liteup("h2", timenow.getHours() % 10);
 6    liteup("m1", Math.floor(timenow.getMinutes() / 10));
 7    liteup("m2", timenow.getMinutes() % 10);
 8    liteup("s1", Math.floor(timenow.getSeconds() / 10));
 9    liteup("s2", timenow.getSeconds() % 10);
10    setTimeout("timeit()"1000);
11}
    首先实例化一个Date对象,分别针对分时秒的十位个位调用上面定义的liteup函数,由于我们的二进制表大约隔一秒钟会跳动一下,所以设定一个推迟器,在这里再次调用此函数,这样二进制表就会不停的跳下去喽。
    运行一下,咦,怎么没有跳动呢,而且浏览器也没有报错呀,摸不到头脑……
    原来timeit的循环是没有问题了,但还没有触发呢,第一次都没有运行起来,后面怎么能够循环呢,好,加入下面一行
1timeit();
    再运行看看,没错,跳动了跳动了,试试你能在一秒内准确的读出时间吗(如果反应时间大于1秒,你将永远读不准时间了,)o(∩_∩)o...哈哈,别灰心习惯了你就能向别人显摆了
    这样就完成了吗,怎么代码长的这么不习惯,跟C似的,没错,这里是个不折不扣的过程编程,今后要是我想加些效果或是其它方面的扩展,还得再加过程,啊,C的噩梦又回来啦?不行,我要面向对象,听说javascript是面向对象的哦,下一篇再改吧,休息,休息……
    
 posted on 2008-02-29 11:22  floodpeak  阅读(2615)  评论(4编辑  收藏  举报