css制作钟表
使用CSS制作钟表
制作一个CSS钟表需要结合HTML结构、CSS样式以及JavaScript动态更新指针位置。以下是详细实现方法:
HTML结构
创建钟表的基本HTML结构,包含表盘、时针、分针和秒针:
<div class="clock">
<div class="clock-face">
<div class="hand hour-hand"></div>
<div class="hand min-hand"></div>
<div class="hand sec-hand"></div>
</div>
</div>
CSS样式
设置钟表的外观和指针样式:
.clock {
width: 300px;
height: 300px;
border: 10px solid #333;
border-radius: 50%;
margin: 50px auto;
position: relative;
}
.clock-face {
width: 100%;
height: 100%;
position: relative;
}
.hand {
width: 50%;
height: 6px;
background: #000;
position: absolute;
top: 50%;
transform-origin: 100%;
transform: rotate(90deg);
transition: transform 0.05s cubic-bezier(0.4, 2.3, 0.3, 1);
}
.hour-hand {
height: 8px;
background: #555;
}
.min-hand {
height: 6px;
background: #777;
}
.sec-hand {
height: 2px;
background: red;
}
JavaScript动态更新
通过JavaScript获取当前时间并更新指针角度:
function updateClock() {
const now = new Date();
const seconds = now.getSeconds();
const minutes = now.getMinutes();
const hours = now.getHours() % 12;
const secDegrees = (seconds / 60) * 360 + 90;
const minDegrees = (minutes / 60) * 360 + (seconds / 60) * 6 + 90;
const hourDegrees = (hours / 12) * 360 + (minutes / 60) * 30 + 90;
document.querySelector('.sec-hand').style.transform = `rotate(${secDegrees}deg)`;
document.querySelector('.min-hand').style.transform = `rotate(${minDegrees}deg)`;
document.querySelector('.hour-hand').style.transform = `rotate(${hourDegrees}deg)`;
}
setInterval(updateClock, 1000);
updateClock(); // 初始化
添加刻度标记
为钟表添加小时刻度:
.clock-face::after {
content: '';
position: absolute;
width: 15px;
height: 15px;
background: #333;
border-radius: 50%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* 添加12个刻度 */
.clock-face {
background: radial-gradient(circle, transparent 60%, #333 60%);
}
.clock-face::before {
content: '';
position: absolute;
width: 100%;
height: 100%;
background: linear-gradient(0deg, transparent 48%, #333 48%, #333 52%, transparent 52%);
background-size: 100% 30px;
}
优化指针动画
使用CSS过渡效果使指针移动更平滑:

.hand {
transition: transform 0.05s cubic-bezier(0.4, 2.3, 0.3, 1);
}
完整实现要点
- 使用
transform-origin: 100%确保指针从中心旋转 - 初始角度设为90度(12点位置)
- 通过JavaScript定时更新指针位置
- 添加刻度增强视觉效果
- 使用CSS过渡实现平滑动画
这种方法创建的钟表会实时显示当前时间,指针每秒更新一次,视觉效果专业且流畅。






