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-dot"></div>
</div>
CSS样式
.clock {
width: 200px;
height: 200px;
border: 10px solid #333;
border-radius: 50%;
position: relative;
background: #fff;
box-shadow: 0 0 10px rgba(0,0,0,0.2);
}
.hour-hand {
width: 6px;
height: 50px;
background: #333;
position: absolute;
top: 50px;
left: 97px;
transform-origin: bottom center;
animation: rotateHour 43200s linear infinite;
}
.minute-hand {
width: 4px;
height: 70px;
background: #666;
position: absolute;
top: 30px;
left: 98px;
transform-origin: bottom center;
animation: rotateMinute 3600s linear infinite;
}
.second-hand {
width: 2px;
height: 80px;
background: #f00;
position: absolute;
top: 20px;
left: 99px;
transform-origin: bottom center;
animation: rotateSecond 60s linear infinite;
}
.center-dot {
width: 10px;
height: 10px;
background: #333;
border-radius: 50%;
position: absolute;
top: 95px;
left: 95px;
}
@keyframes rotateHour {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
@keyframes rotateMinute {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
@keyframes rotateSecond {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
添加时钟刻度
为时钟添加刻度可以增强真实感:
.clock::before {
content: '';
position: absolute;
width: 8px;
height: 8px;
background: #333;
border-radius: 50%;
top: 10px;
left: 96px;
}
.clock::after {
content: '';
position: absolute;
width: 8px;
height: 8px;
background: #333;
border-radius: 50%;
bottom: 10px;
left: 96px;
}
.clock span {
position: absolute;
width: 8px;
height: 8px;
background: #333;
border-radius: 50%;
}
.clock span:nth-child(1) {
top: 96px;
right: 10px;
}
.clock span:nth-child(2) {
top: 96px;
left: 10px;
}
使用JavaScript实现实时时间
为让时钟显示真实时间,可以添加JavaScript:
function updateClock() {
const now = new Date();
const hours = now.getHours() % 12;
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const hourDegrees = (hours * 30) + (minutes * 0.5);
const minuteDegrees = minutes * 6;
const secondDegrees = seconds * 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 {
/* 原有样式 */
box-shadow:
inset 0 0 15px rgba(0,0,0,0.1),
0 5px 15px rgba(0,0,0,0.3);
}
.hour-hand {
/* 原有样式 */
box-shadow: 0 0 5px rgba(0,0,0,0.3);
}
.minute-hand {
/* 原有样式 */
box-shadow: 0 0 5px rgba(0,0,0,0.3);
}
.second-hand {
/* 原有样式 */
box-shadow: 0 0 5px rgba(0,0,0,0.3);
}
通过以上方法可以创建一个功能完整、视觉效果良好的CSS3时钟。可以根据需要调整尺寸、颜色和动画效果来满足不同设计需求。







