<!DOCTYPE html> <html> <body onload="startTime()"> <h2>JavaScript 时钟</h2> <div id="txt"></div> <script> function startTime() { const today = new Date(); let h = today.getHours(); let m = today.getMinutes(); let s = today.getSeconds(); m = checkTime(m); s = checkTime(s); document.getElementById('txt').innerHTML = h + ":" + m + ":" + s; setTimeout(startTime, 1000); } function checkTime(i) { if (i < 10) {i = "0" + i}; // 在小于 10 的数字前加零 return i; } </script> </body> </html>