1. 程式人生 > >案例:利用JS動態的顯示當前時間

案例:利用JS動態的顯示當前時間

<!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>
</head>
<body>
<input type="text" id="showTime"/>
<input type="button" onclick="clock()" value="getNowTime"/>
<script type="text/javascript">
		function clock(){
			
			//分別獲取時分秒
			var date = new Date();
			var hours = date.getHours();
			var minu = date.getMinutes();
			var sed = date.getSeconds();
			
			//檢查時間為個位數時,前面加0,如9---09
			hours = check(hours);
			minu = check(minu);
			sed = check(sed);
			
			var strDate = hours + ":" + minu + ":" + sed;
			var textTime = document.getElementById("showTime");
			
			//進行清空
			textTime.value = "";
			textTime.value = strDate;
			
			//計時器,每500ms重新整理一次
			window.setTimeout("clock()","500");	
			}
			
		function check(date){
			if (0<=date && date <=9){
				date = "0" + date;
				return date;
				}
			else{
				return date;
				}
			}
</script>
</body>
</html>