css3制作时钟样式
使用CSS3制作时钟样式
通过CSS3的动画和变换特性,可以创建一个动态的时钟样式。以下是实现方法:
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: 200px;
height: 200px;
border: 10px solid #333;
border-radius: 50%;
position: relative;
background: #fff;
}
.hour-hand {
width: 6px;
height: 50px;
background: #333;
position: absolute;
top: 50px;
left: 97px;
transform-origin: bottom center;
animation: rotate 43200s linear infinite;
}
.minute-hand {
width: 4px;
height: 70px;
background: #666;
position: absolute;
top: 30px;
left: 98px;
transform-origin: bottom center;
animation: rotate 3600s linear infinite;
}
.second-hand {
width: 2px;
height: 90px;
background: #f00;
position: absolute;
top: 10px;
left: 99px;
transform-origin: bottom center;
animation: rotate 60s linear infinite;
}
.center {
width: 12px;
height: 12px;
background: #333;
border-radius: 50%;
position: absolute;
top: 94px;
left: 94px;
}
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
添加时钟刻度
为了增强时钟的真实感,可以添加小时刻度:
.clock::before {
content: '';
position: absolute;
width: 8px;
height: 15px;
background: #333;
top: 0;
left: 96px;
}
.clock::after {
content: '';
position: absolute;
width: 8px;
height: 15px;
background: #333;
bottom: 0;
left: 96px;
}
响应式设计
使时钟适应不同屏幕尺寸:
@media (max-width: 600px) {
.clock {
width: 150px;
height: 150px;
border-width: 8px;
}
.hour-hand {
height: 40px;
top: 35px;
left: 72px;
}
.minute-hand {
height: 60px;
top: 15px;
left: 73px;
}
.second-hand {
height: 70px;
top: 5px;
left: 74px;
}
.center {
width: 10px;
height: 10px;
top: 70px;
left: 70px;
}
}
使用JavaScript实现实时更新
对于更精确的时间显示,可以结合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 = `rotate(${hourDeg}deg)`;
document.querySelector('.minute-hand').style.transform = `rotate(${minuteDeg}deg)`;
document.querySelector('.second-hand').style.transform = `rotate(${secondDeg}deg)`;
}
setInterval(updateClock, 1000);
updateClock();
美化时钟样式
添加阴影和渐变效果增强视觉体验:
.clock {
box-shadow: 0 0 20px rgba(0,0,0,0.3);
background: radial-gradient(circle, #fff 0%, #eee 100%);
}
.hour-hand {
box-shadow: 0 0 5px rgba(0,0,0,0.5);
}
.minute-hand {
box-shadow: 0 0 4px rgba(0,0,0,0.4);
}
.second-hand {
box-shadow: 0 0 3px rgba(0,0,0,0.3);
}






