css动画时钟制作
CSS动画时钟制作步骤
创建HTML结构
使用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: 10px solid #333;
border-radius: 50%;
position: relative;
margin: 50px auto;
background: #fff;
}
.hour-hand, .minute-hand, .second-hand {
position: absolute;
background: #000;
transform-origin: bottom center;
left: 50%;
bottom: 50%;
}
.hour-hand {
width: 8px;
height: 80px;
margin-left: -4px;
}
.minute-hand {
width: 5px;
height: 120px;
margin-left: -2.5px;
}
.second-hand {
width: 2px;
height: 140px;
margin-left: -1px;
background: red;
}
.center {
width: 20px;
height: 20px;
background: #333;
border-radius: 50%;
position: absolute;
left: 50%;
top: 50%;
margin-left: -10px;
margin-top: -10px;
z-index: 10;
}
添加动画效果
使用CSS动画让指针随时间旋转,通过@keyframes定义旋转动画。
.second-hand {
animation: rotate 60s linear infinite;
}
.minute-hand {
animation: rotate 3600s linear infinite;
}
.hour-hand {
animation: rotate 43200s linear infinite;
}
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
精确时间同步
通过JavaScript获取当前时间,并动态调整指针的初始位置。

function updateClock() {
const now = new Date();
const seconds = now.getSeconds();
const minutes = now.getMinutes();
const hours = now.getHours() % 12;
const secondDegrees = seconds * 6;
const minuteDegrees = minutes * 6 + seconds * 0.1;
const hourDegrees = hours * 30 + minutes * 0.5;
document.querySelector('.second-hand').style.transform = `rotate(${secondDegrees}deg)`;
document.querySelector('.minute-hand').style.transform = `rotate(${minuteDegrees}deg)`;
document.querySelector('.hour-hand').style.transform = `rotate(${hourDegrees}deg)`;
}
setInterval(updateClock, 1000);
updateClock();
优化动画流畅度
使用transform代替top或left属性,确保动画性能流畅。
.second-hand, .minute-hand, .hour-hand {
will-change: transform;
}
添加刻度标记
在表盘上添加小时和分钟刻度,增强视觉效果。
<div class="clock">
<!-- 添加刻度 -->
<div class="mark mark-12"></div>
<div class="mark mark-3"></div>
<div class="mark mark-6"></div>
<div class="mark mark-9"></div>
<!-- 指针和中心点 -->
</div>
.mark {
position: absolute;
background: #333;
width: 4px;
height: 15px;
left: 50%;
bottom: 50%;
margin-left: -2px;
transform-origin: bottom center;
}
.mark-12 { transform: rotate(0deg); }
.mark-3 { transform: rotate(90deg); }
.mark-6 { transform: rotate(180deg); }
.mark-9 { transform: rotate(270deg); }






