css怎么制作时钟
使用CSS制作时钟
使用CSS和少量JavaScript可以制作一个简单的时钟。以下是实现方法:
基本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;
margin: 50px auto;
}
.hour-hand, .minute-hand, .second-hand {
position: absolute;
background: #333;
transform-origin: bottom center;
left: 50%;
top: 50%;
}
.hour-hand {
width: 6px;
height: 60px;
margin-left: -3px;
margin-top: -60px;
}
.minute-hand {
width: 4px;
height: 80px;
margin-left: -2px;
margin-top: -80px;
}
.second-hand {
width: 2px;
height: 90px;
margin-left: -1px;
margin-top: -90px;
background: red;
}
.center-dot {
width: 12px;
height: 12px;
background: #333;
border-radius: 50%;
position: absolute;
left: 50%;
top: 50%;
margin-left: -6px;
margin-top: -6px;
z-index: 10;
}
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::before {
content: '';
position: absolute;
width: 100%;
height: 100%;
border-radius: 50%;
}
.clock::after {
content: '';
position: absolute;
width: 100%;
height: 100%;
border-radius: 50%;
transform: rotate(30deg);
}
.clock::before, .clock::after {
background: linear-gradient(
to right,
transparent 48%,
#333 48%,
#333 52%,
transparent 52%
);
}
完整实现步骤
- 创建圆形时钟表盘
- 添加时针、分针和秒针
- 设置指针的旋转中心在底部
- 使用JavaScript获取当前时间
- 计算各指针应旋转的角度
- 每秒更新指针位置
- 可选添加时钟刻度装饰
进阶优化
/* 添加阴影效果 */
.clock {
box-shadow: 0 0 15px rgba(0,0,0,0.2);
}
/* 添加数字刻度 */
.number {
position: absolute;
width: 100%;
height: 100%;
text-align: center;
font-size: 18px;
font-weight: bold;
}
/* 平滑动画过渡 */
.hour-hand, .minute-hand, .second-hand {
transition: transform 0.5s cubic-bezier(0.4, 2.3, 0.3, 1);
}
通过以上CSS和JavaScript的组合,可以创建一个功能完整且美观的时钟效果。







