DOM案例【1】文本時鐘
阿新 • • 發佈:2018-01-14
ring tle 位數 date() 時間顯示 檢查 ret urn col
1.網絡參考
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <title></title> </head> <body> <p id="timer">時間顯示</p> </body> </html> <script language="javascript" type="text/javascript"> //間隔計時器或者單次計時器 window.onload = function () { setInterval(showtime, 10); } //補全分秒的個位數 function checktime(time) { if (time < 10) time = ‘0‘ + time; return time; } function showtime() { //輸出星期需要轉換顯示格式var weeks = [‘星期日‘, ‘星期一‘, ‘星期二‘, ‘星期三‘, ‘星期四‘, ‘星期五‘, ‘星期六‘]; var mytime = new Date(), timer = document.getElementById("timer"); //JS月份從0起算,需要加一 var mon = mytime.getMonth() + 1; var hou = checktime(mytime.getHours()), min = checktime(mytime.getMinutes()), sec= checktime(mytime.getSeconds()); timer.innerHTML = mytime.getFullYear() + "年" + mon + "月" + mytime.getDate() + "日 " + weeks[mytime.getDay()] + " " + hou + ":" + min + ":" + sec; //setTimeout(showtime,10); } </script>
2.個人實現
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <div id="timer"></div> </body> </html> <script type="text/javascript"> //檢查時間,補零 function checkTime(time) { if (time < 10) { time = "0" + time; } return time; } //獲取當前時間 function getTimeString() { var date = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; if (month < 10) { month = "0" + month; } var day = checkTime(date.getDate()); var hour = checkTime(date.getHours()); var minute = checkTime(date.getMinutes()); var second = checkTime(date.getSeconds()); var timeString = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second; return timeString; } setInterval(function () { var res = getTimeString(); document.getElementById("timer").innerHTML = res; }, 1000); </script>
DOM案例【1】文本時鐘