JavaScript动态网页-时钟

设计思路:1.先建立一个数组保存带有0~9数字的10张图片;

2.通过getDate()获得本地时间保存在变量myTime中;

3.getHours()返回的是24进制即0~23的整数,getMinutes()方法返回一个处于 0 到 59 之间的整数,getSeconds()方法返回一个处于 0 到 59 之间的整数;

4.通过setTimeout()每隔1秒调用一次show()函数改变image对象的src属性。

string对象的charAt(id)方法:返回指定位置处的字符,id为要寻找的字符的位置的索引整数,0对应左边第1个字符,1对应左边第2个字符,如hello的charAt(1)则是e;

代码如下: 

<html>
<head>
<title>时钟</title>
<meta charset="utf-8">
<style>
*{
	padding:0;
	margin:0;
	}
</style>
<script>
function show(){
	var images=new Array("./images/s0.png","./images/s1.png","./images/s2.png","./images/s3.png","./images/s4.png","./images/s5.png","./images/s6.png","./images/s7.png","./images/s8.png","./images/s9.png");
	var myTime=new Date();
	var hours=myTime.getHours();
	var minutes=myTime.getMinutes();
	var seconds=myTime.getSeconds();
	if(hours<=9){hours="0"+hours;}//补足两位
	if(minutes<=9){minutes="0"+minutes;}
	if(seconds<=9){seconds="0"+seconds}
	var theString=""+hours+minutes+seconds;//转换为字符串
	document.getElementById("img0").src=images[theString.charAt(0)];
	document.getElementById("img1").src=images[theString.charAt(1)];
	document.getElementById("img2").src=images[theString.charAt(2)];
	document.getElementById("img3").src=images[theString.charAt(3)];
	document.getElementById("img4").src=images[theString.charAt(4)];
	document.getElementById("img5").src=images[theString.charAt(5)];
	setTimeout("show()",1000);
	}
</script>
</head>
<body onLoad="show()">
<img id="img0" /><img id="img1" />时<img id="img2" /><img id="img3" />分<img id="img4" /><img id="img5" />
</body>
</html>

网页实现如下图:

猜你喜欢

转载自blog.csdn.net/Cairo960918/article/details/82503143
今日推荐