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"></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: 50px;
margin-left: -3px;
margin-top: -50px;
}
.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 {
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 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();
实现原理
时钟的指针通过 CSS 的 transform: rotate() 属性实现旋转。JavaScript 计算当前时间对应的角度,每小时对应 30 度(360/12),每分钟对应 6 度(360/60),秒针同理。
transform-origin: bottom center 确保指针围绕底部中心旋转。定时器每秒更新一次指针位置,实现动态效果。
增强样式
可以添加时钟刻度和数字增强视觉效果:
.clock::before {
content: '';
position: absolute;
width: 4px;
height: 12px;
background: #333;
left: 50%;
top: 10px;
margin-left: -2px;
}
/* 添加其他刻度类似 */
这种方法创建的时钟简洁高效,适合大多数网页场景。







