本文實例講解了javascript實現動態顯示當前系統時間的詳細代碼,具體內容如下
效果圖:
具體代碼:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>無標題文檔</title> <script type="text/javascript"> //定義函數:構建要顯示的時間日期字符串 function showTime() { //創建Date對象 var today = new Date(); //分別取出年、月、日、時、分、秒 var year = today.getFullYear(); var month = today.getMonth()+1; var day = today.getDate(); var hours = today.getHours(); var minutes = today.getMinutes(); var seconds = today.getSeconds(); //如果是單個數,則前面補0 month = month<10 ? "0"+month : month; day = day <10 ? "0"+day : day; hours = hours<10 ? "0"+hours : hours; minutes = minutes<10 ? "0"+minutes : minutes; seconds = seconds<10 ? "0"+seconds : seconds; //構建要輸出的字符串 var str = year+"年"+month+"月"+day+"日 "+hours+":"+minutes+":"+seconds; //獲取id=result的對象 var obj = document.getElementById("result"); //將str的內容寫入到id=result的<div>中去 obj.innerHTML = str; //延時器 window.setTimeout("showTime()",1000); } </script> <style type="text/css"> #result{ width:500px; border:1px solid #CCCCCC; background:#FFFFCC; margin:50px auto; font-size:24px; color:#FF0000; padding:20px; } </style> </head> <body onload="showTime()"> <div id="result"></div> </body> </html>
希望本文所述對大家的javascript程序設計有所幫助。