css制作时钟

使用CSS制作时钟的方法
基本HTML结构
<div class="clock">
<div class="hour-hand"></div>
<div class="minute-hand"></div>
<div class="second-hand"></div>
<div class="center"></div>
</div>
CSS样式设置
.clock {
width: 300px;
height: 300px;
border-radius: 50%;
background-color: #f0f0f0;
position: relative;
margin: 50px auto;
border: 10px solid #333;
}
.hour-hand {
width: 8px;
height: 80px;
background-color: #333;
position: absolute;
top: 30%;
left: 50%;
transform-origin: bottom center;
transform: translateX(-50%) rotate(0deg);
}
.minute-hand {
width: 4px;
height: 120px;
background-color: #666;
position: absolute;
top: 20%;
left: 50%;
transform-origin: bottom center;
transform: translateX(-50%) rotate(0deg);
}
.second-hand {
width: 2px;
height: 140px;
background-color: red;
position: absolute;
top: 10%;
left: 50%;
transform-origin: bottom center;
transform: translateX(-50%) rotate(0deg);
}
.center {
width: 12px;
height: 12px;
background-color: #333;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
添加刻度标记
.clock::after {
content: '';
position: absolute;
width: 5px;
height: 15px;
background-color: #333;
top: 0;
left: 50%;
transform: translateX(-50%);
}
.clock::before {
content: '';
position: absolute;
width: 5px;
height: 15px;
background-color: #333;
bottom: 0;
left: 50%;
transform: translateX(-50%);
}
使用CSS动画实现指针移动
@keyframes rotate {
100% {
transform: translateX(-50%) rotate(360deg);
}
}
.second-hand {
animation: rotate 60s linear infinite;
}
.minute-hand {
animation: rotate 3600s linear infinite;
}
.hour-hand {
animation: rotate 43200s linear infinite;
}
添加数字刻度
<div class="clock">
<!-- 指针元素 -->
<span class="number" style="top: 10%; left: 50%;">12</span>
<span class="number" style="top: 50%; right: 10%;">3</span>
<span class="number" style="bottom: 10%; left: 50%;">6</span>
<span class="number" style="top: 50%; left: 10%;">9</span>
</div>
.number {
position: absolute;
transform: translate(-50%, -50%);
font-size: 20px;
font-weight: bold;
}
使用JavaScript实现实时更新
function updateClock() {
const now = new Date();
const hours = now.getHours() % 12;
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const hourDeg = (hours * 30) + (minutes * 0.5);
const minuteDeg = minutes * 6;
const secondDeg = seconds * 6;
document.querySelector('.hour-hand').style.transform =
`translateX(-50%) rotate(${hourDeg}deg)`;
document.querySelector('.minute-hand').style.transform =
`translateX(-50%) rotate(${minuteDeg}deg)`;
document.querySelector('.second-hand').style.transform =
`translateX(-50%) rotate(${secondDeg}deg)`;
}
setInterval(updateClock, 1000);
updateClock();
完整实现要点
- 使用圆形div作为时钟表盘
- 创建三个矩形div分别作为时针、分针和秒针
- 通过transform-origin设置旋转中心点
- 使用CSS动画或JavaScript控制指针旋转
- 添加刻度标记和数字增强视觉效果
- 通过JavaScript获取当前时间并计算指针角度
这种方法可以创建出美观且功能完整的CSS时钟,既可以使用纯CSS动画实现,也可以通过JavaScript实现更精确的时间同步。






