本文執行個體講述了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程式設計有所協助。