JavaScript获取时间小demo【计时器】

 JavaScript获取时间的小例子,和JavaScript定时器简单使用。

/**
 * @author xuweikai
 */
function $(id) {
  return document.getElementById(id);
}


//设置辅助函数,当所得值小于10的时候在前面补一个0;
function Timehelp (n) {
  return n<10?"0"+n:n;
}


function showTime() {
	var time = new Date();//得到当前时间
	//得到当前时间年月日
	titel = "现在是:";
  	titel += time.getFullYear() + "年";
  	titel += Timehelp((time.getMonth()+1)) +"月";
  	titel += Timehelp(time.getDate()) +"日";
  	titel += "星期"+["日","一","二","三","四","五","六"][time.getDay()];
  	//将当前时间加到html页面中
  	$("titel").innerHTML = titel;
  	//得到当前的时分秒;
  	var center = time.getHours() + ":";
  	center += Timehelp(time.getMinutes())+":";
  	center += Timehelp(time.getSeconds());
  	$("time").innerHTML = center;
  	//设置定时器;
  	dinshiqi = setTimeout(showTime,1000);
  	
}


//当页面加载完毕后执行当前函数;
window.onload = function() {
	//调用上面时间函数;
	showTime();
	//为按钮添加开始事件;
	$("start").onclick = function statr(){
	
	showTime();
}
	//为按钮添加停止事件;
	$("stop").onclick = function stop(){
		clearTimeout();
	}
}


页面简单的样式.css

#mydiv {
	width: 600px;
	height: 400px;
	background-color: #c8c8c8;
	margin:50px auto;
}
#titel{
	font-size: 36px;
	font-family: "隶书";
	background-color: #2845b2;
	color: #ffffff;
/*	color: red;*/
	text-align: center;
	height: 60px;
	line-height: 60px;
}

#time{
	font-size: 80px;
	height: 250px;
	line-height: 250px; 
	text-align: center;
	
	
}

#mybutton{
	width: 600px;
	height: 30px;
/*	background-color: #2845b2;*/
	line-height: 30px;
	text-align: center;
}

计时器页面:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>计时器</title>
		<script language="JavaScript" src="js/time.js"></script> 
		<link rel="stylesheet"  href="css/timer.css" />
	</head>
	<body>
		<div id="mydiv">
				<h1 id="titel"></h1>
				<div id="time"></div>
			<div id="mybutton">
				<input type="button" id="start" value="开始" />
				<input type="button" id="stop" value="停止" />
			</div>
		</div>
	</body>
</html>


页面效果:




  希望对初学JavaScript的同学有帮助。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值