<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
function zr(n)//将数字转换成字符串并在一位数前添‘0’
{
if(n<10)
{
return '0'+n;
}
else
{
return ''+n; //前面加空字符能保证它返回的一定是个字符串而不是数字
}
}
window.onload=function()
{
var oDiv1=document.getElementById('div1');
var oDiv2=document.getElementById('div2');
var aImg1=oDiv1.getElementsByTagName('img');
var aImg2=oDiv2.getElementsByTagName('img');
function clock()
{
var oDate = new Date();
var str1=zr(oDate.getFullYear())+zr(oDate.getMonth()+1)+zr(oDate.getDate());//获取系统日期,并转换成字符串
var str2=zr(oDate.getHours())+zr(oDate.getMinutes())+zr(oDate.getSeconds());//获取系统时间,并转换成字符串
for(var i=0; i<aImg1.length; i++)//更改img下的图片
{
aImg1[i].src='img09/'+str1.charAt(i)+'.png';//此处用charAt能做到全兼容,如用str1[i]部分浏览器不兼容
}
for(var i=0; i<aImg2.length; i++)//更改img下的图片
{
aImg2[i].src='img09/'+str2.charAt(i)+'.png';
}
}
setInterval(clock,500);//这里我们在定时器里面调用clock函数,如果我们偷懒将clock函数直接写在setInterval里面,下面我们将无法调用clock函数
clock();//由于定时器不会在打开网页的时候立即执行定时器里面的代码,我们需要在此处调用clock函数,让它立即执行一次,防止刷新网页的时候出现全‘0’的现象(由于我的img标签的src默认值是0.png(数字‘0’))
}
</script>
</head>
<body style="background:#000; font-size:100px; color:#FFF">
<div id="div1">
<img src="img09/0.png" />
<img src="img09/0.png" />
<img src="img09/0.png" />
<img src="img09/0.png" />
年
<img src="img09/0.png" />
<img src="img09/0.png" />
月
<img src="img09/0.png" />
<img src="img09/0.png" />
日
</div>
<div id="div2">
<img src="img09/0.png" />
<img src="img09/0.png" />
:
<img src="img09/0.png" />
<img src="img09/0.png" />
:
<img src="img09/0.png" />
<img src="img09/0.png" />
</div>
</body>
</html>
如果我们将定时器写成这样将无法在下面调用clock函数
setInterval(function clock()
{
var oDate = new Date();
var str1=zr(oDate.getFullYear())+zr(oDate.getMonth()+1)+zr(oDate.getDate());
var str2=zr(oDate.getHours())+zr(oDate.getMinutes())+zr(oDate.getSeconds());
for(var i=0; i<aImg1.length; i++)
{
aImg1[i].src='img09/'+str1.charAt(i)+'.png';
}
for(var i=0; i<aImg2.length; i++)
{
aImg2[i].src='img09/'+str2.charAt(i)+'.png';
}
}
,500);
clock();//这里无法调用clock函数
}