DIV CSS 佈局教程網

JavaScript實現模擬時鐘的方法
編輯:JavaScript綜合知識     

本文分享一個用JavaScript實現模擬時鐘的實例,供有需要的朋友參考。具體實現如下:

這個示例用到了JavaScript內建對象Date的getFullYear、getMonth和getDate方法。首先聲明一個變量d(var d = new Date()),表示將當天的日期值賦給變量d。然後用getFullYear得到年份值,用getMonth得到月份值(註:getMonth返回值範圍為0到11,所以要得到實際月份還要加1),用getDate得到當天日期。示例還用到了"test?語句1:語句2"的三元運算,如果月和日小於10,就在前面加0補零。

<html xmlns="https://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>javascript模擬時鐘</title>
  <script type="text/javascript">
  function Format2Len(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程序設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved