您的位置:首页 > Web前端 > JavaScript

javascript实现模拟时钟的方法

2015-05-13 00:00 806 查看
本文实例讲述了javascript实现模拟时钟的方法。分享给大家供大家参考。具体实现方法如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>javascript模拟时钟</title>
 <!--Javascript示例代码解释:
 这个示例用到了Javascript内置对象Date的getFullYear,
 getMonth和getDate方法。首先申明一个变量d,var d = new Date(),
 表示将当天的日期值赋给变量d。然后使用getFullYear得到年份的值,
 用getMonth得到月份值(注:getMonth返回值范围为0到11,
 所以要得到实际的月份,还要加1),
 用getDate得到当天日期所在月份的日期值。
 这个示例还用到了"test?语句1:语句2",
 意思是如果符合test条件,那么执行语句1,
 否则使用语句2。计算月和日都用到了这个语法,
 如果月和日小于10,在月和日的值之前应该加0。=-->
 <script type="text/javascript">
  function Format2Len(i) {
//   if (i < 10) {
//    return "0" + i;
//   }
//   else {
//    return i;
   //   }
   return i < 10 ? "0" + i : i;
  }
  function RefreshClock() {
   var CurrentTime = new Date();
   var timeStr = CurrentTime.getFullYear() + "-" +
     Format2Len(CurrentTime.getMonth()+1) + "-" +
     Format2Len(CurrentTime.getDate()) + " " +
     Format2Len(CurrentTime.getHours()) + ":" +
     Format2Len(CurrentTime.getMinutes()) + ":" +
     Format2Len(CurrentTime.getSeconds());
   txtClock.value = timeStr;
  }
  setInterval("RefreshClock()", 1000);
 </script>
</head>
<body onload="RefreshClock()">
<!--页面加载的时候执行一次-->
 当前时间:<input type="text" id="txtClock" />
</body>
</html>


希望本文所述对大家的javascript程序设计有所帮助。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: