css时钟制作
使用CSS和HTML创建时钟
创建一个CSS时钟需要结合HTML、CSS和JavaScript来实现动态效果。以下是实现步骤:
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;
}
.hour-hand, .minute-hand, .second-hand {
position: absolute;
background: #333;
transform-origin: bottom center;
}
.hour-hand {
width: 8px;
height: 80px;
top: 70px;
left: 146px;
}
.minute-hand {
width: 4px;
height: 120px;
top: 30px;
left: 148px;
}
.second-hand {
width: 2px;
height: 140px;
top: 10px;
left: 149px;
background: red;
}
.center {
width: 20px;
height: 20px;
background: #333;
border-radius: 50%;
position: absolute;
top: 140px;
left: 140px;
}
JavaScript动态更新
function updateClock() {
const now = new Date();
const hour = now.getHours() % 12;
const minute = now.getMinutes();
const second = now.getSeconds();
const hourDegrees = (hour * 30) + (minute * 0.5);
const minuteDegrees = minute * 6;
const secondDegrees = second * 6;
document.querySelector('.hour-hand').style.transform = `rotate(${hourDegrees}deg)`;
document.querySelector('.minute-hand').style.transform = `rotate(${minuteDegrees}deg)`;
document.querySelector('.second-hand').style.transform = `rotate(${secondDegrees}deg)`;
}
setInterval(updateClock, 1000);
updateClock();
添加时钟刻度和数字
为了增强时钟的真实感,可以添加刻度和数字:

.clock::before {
content: '';
position: absolute;
width: 280px;
height: 280px;
border-radius: 50%;
top: 10px;
left: 10px;
}
.clock::after {
content: '';
position: absolute;
width: 260px;
height: 260px;
border-radius: 50%;
top: 20px;
left: 20px;
}
/* 添加刻度 */
.clock .mark {
position: absolute;
width: 4px;
height: 15px;
background: #333;
top: 0;
left: 148px;
transform-origin: bottom center;
}
/* 添加数字 */
.clock .number {
position: absolute;
font-size: 24px;
font-weight: bold;
color: #333;
transform-origin: center center;
}
使用CSS动画实现平滑移动
为了让指针移动更平滑,可以添加CSS过渡效果:
.hour-hand, .minute-hand, .second-hand {
transition: transform 0.3s cubic-bezier(0.4, 2.3, 0.3, 1);
}
纯CSS时钟(无JavaScript)
使用CSS动画也可以创建时钟,但精度较低:
.hour-hand {
animation: rotate-hour 43200s infinite linear;
}
.minute-hand {
animation: rotate-minute 3600s infinite linear;
}
.second-hand {
animation: rotate-second 60s infinite linear;
}
@keyframes rotate-hour {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
@keyframes rotate-minute {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
@keyframes rotate-second {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
响应式设计
确保时钟在不同设备上都能正常显示:
@media (max-width: 600px) {
.clock {
width: 200px;
height: 200px;
}
.hour-hand {
height: 50px;
top: 50px;
}
.minute-hand {
height: 80px;
top: 20px;
}
.second-hand {
height: 90px;
top: 10px;
}
}






