<!DOCTYPE html>
<html>
<head>
<title>JavaScript Clock</title>
<style>
body {
font-family: sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
#clock {
font-size: 2em;
padding: 20px;
border-radius: 10px;
background-color: #fff;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
</style>
</head>
<body>
<div id="clock"></div>
<script>
function updateClock() {
const now = new Date();
let hours = now.getHours();
let minutes = now.getMinutes();
let seconds = now.getSeconds();
// Add leading zeros if needed
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
const timeString = hours + ":" + minutes + ":" + seconds;
document.getElementById("clock").textContent = timeString;
}
// Update the clock every second
setInterval(updateClock, 1000);
// Initial clock update
updateClock();
</script>
</body>
</html>
This code creates a simple digital clock that displays the current time in HH:MM:SS format. Here's a breakdown:
-
HTML Structure: Sets up a basic HTML page with a
div
element where the clock will be displayed. Styling is included to center the clock and give it a clean look. -
updateClock()
Function: This function gets the current time usingnew Date()
, extracts the hours, minutes, and seconds, adds leading zeros if necessary (e.g., "09" instead of "9"), and formats the time string. It then updates the content of theclock
div with the formatted time. -
setInterval()
: This function callsupdateClock()
every 1000 milliseconds (1 second), ensuring the clock updates continuously. -
updateClock()
Initial Call: This line callsupdateClock()
once when the page loads to initially set the clock's time.
Key improvements over simpler alternatives:
- Leading Zeros: Ensures a consistent and visually appealing time format (e.g., "03:07:02" instead of "3:7:2").
- Clearer Code Structure: Uses a separate function for updating the clock, making the code more organized and readable.
- Styling: Basic CSS is included to make the clock look presentable.
This improved version provides a more complete and robust solution for a basic JavaScript clock. You can easily customize the styling further to match your website's design.
标签:hours,clock,seconds,程序,js,updateClock,time,minutes,时钟 From: https://www.cnblogs.com/ai888/p/18580867