這篇文章主要介紹了javascript實現模擬時鐘的方法,涉及javascript操作時間實時顯示的相關技巧,需要的朋友可以參考下
本文實例講述了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程序設計有所幫助。
新聞熱點
疑難解答
圖片精選