HTML5數字時鐘時分秒代碼
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>數字時鐘</title> <style> #clock { font-size: 5rem; font-family: Arial; text-align: center; } </style> </head> <body> <div id="clock"></div> <script> function getTime() { const now = new Date(); const hours = now.getHours(); const minutes = now.getMinutes(); const seconds = now.getSeconds(); const time = `${hours}:${minutes}:${seconds}`; document.getElementById('clock').innerHTML = time; } setInterval(getTime, 1000); </script> </body> </html>
代碼解釋:
1. HTML5聲明 <!DOCTYPE html> 2. html標簽開始 <html> 3. head標簽開始 <head> 4. 設置字符集 <meta charset="utf-8"> 5. 設置網頁標題 <title>數字時鐘</title> 6. 內聯樣式,設置數字時鐘樣式 <style> #clock { font-size: 5rem; font-family: Arial; text-align: center; } </style> 7. head標簽結束 </head> 8. body標簽開始 <body> 9. 創建數字時鐘區域 <div id="clock"></div> 10. Javascript腳本,獲取當前時間并設置時間格式 <script> function getTime() { const now = new Date(); const hours = now.getHours(); const minutes = now.getMinutes(); const seconds = now.getSeconds(); const time = `${hours}:${minutes}:${seconds}`; document.getElementById('clock').innerHTML = time; } setInterval(getTime, 1000); //每1000毫秒(即1秒)執行一次getTime函數 </script> 11. body標簽結束 </body> 12. html標簽結束 </html>