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();
}
}
#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的同学有帮助。