js 时钟实现
实现 JavaScript 时钟的步骤
基础 HTML 结构
创建一个简单的 HTML 文件,包含一个用于显示时间的元素。
<!DOCTYPE html>
<html>
<head>
<title>JavaScript 时钟</title>
<style>
#clock {
font-size: 48px;
text-align: center;
margin-top: 100px;
}
</style>
</head>
<body>
<div id="clock"></div>
<script src="clock.js"></script>
</body>
</html>
JavaScript 核心逻辑
在 clock.js 文件中编写时钟更新的逻辑。
function updateClock() {
const now = new Date();
const hours = now.getHours().toString().padStart(2, '0');
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
const timeString = `${hours}:${minutes}:${seconds}`;
document.getElementById('clock').textContent = timeString;
}
// 初始调用
updateClock();
// 每秒更新一次
setInterval(updateClock, 1000);
添加日期显示
扩展功能以包含日期信息。

function updateClock() {
const now = new Date();
// 时间部分
const hours = now.getHours().toString().padStart(2, '0');
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
// 日期部分
const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const day = now.getDate().toString().padStart(2, '0');
const timeString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
document.getElementById('clock').textContent = timeString;
}
样式优化
为时钟添加更多视觉效果。
#clock {
font-family: 'Arial', sans-serif;
font-size: 48px;
text-align: center;
margin-top: 100px;
color: #333;
background: #f5f5f5;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
width: 300px;
margin-left: auto;
margin-right: auto;
}
12 小时制支持
添加切换 12/24 小时制的功能。

let is12HourFormat = false;
function toggleFormat() {
is12HourFormat = !is12HourFormat;
updateClock();
}
function updateClock() {
const now = new Date();
let hours = now.getHours();
if (is12HourFormat) {
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // 处理 0 点的情况
hours = hours.toString().padStart(2, '0');
const timeString = `${hours}:${minutes}:${seconds} ${ampm}`;
document.getElementById('clock').textContent = timeString;
} else {
// 保持原来的 24 小时制逻辑
}
}
添加切换按钮
在 HTML 中添加格式切换按钮。
<div id="clock"></div>
<button onclick="toggleFormat()">切换 12/24 小时制</button>
最终效果
完整的 JavaScript 时钟实现包含以下功能:
- 实时显示时间(时:分:秒)
- 可选的日期显示
- 12/24 小时制切换
- 基本的样式美化
- 每秒自动更新
这个实现可以根据需要进一步扩展,例如添加时区支持、更多样式选项或动画效果。






