css制作模拟时钟
CSS 制作模拟时钟
模拟时钟可以通过 CSS 和 JavaScript 结合实现,主要利用 transform 和 transition 属性来模拟时针、分针和秒针的旋转效果。
HTML 结构
时钟的基本结构包括一个外框和三个指针(时针、分针、秒针):

<div class="clock">
<div class="hour-hand"></div>
<div class="minute-hand"></div>
<div class="second-hand"></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-color: #333;
transform-origin: bottom center;
}
.hour-hand {
width: 6px;
height: 60px;
top: 50px;
left: 97px;
}
.minute-hand {
width: 4px;
height: 80px;
top: 30px;
left: 98px;
}
.second-hand {
width: 2px;
height: 90px;
top: 20px;
left: 99px;
background-color: red;
}
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(); // 初始化时钟
优化指针动画
为指针添加平滑的过渡效果:
.hour-hand, .minute-hand, .second-hand {
transition: transform 0.3s cubic-bezier(0.4, 2.3, 0.3, 1);
}
添加刻度
为时钟添加小时刻度,增强视觉效果:
.clock::after {
content: '';
position: absolute;
width: 10px;
height: 10px;
background-color: #333;
border-radius: 50%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* 刻度标记 */
.clock .mark {
position: absolute;
width: 4px;
height: 15px;
background-color: #333;
left: 98px;
transform-origin: bottom center;
}
/* 每 30 度一个刻度 */
.clock .mark:nth-child(1) { transform: rotate(30deg) translateY(-90px); }
.clock .mark:nth-child(2) { transform: rotate(60deg) translateY(-90px); }
.clock .mark:nth-child(3) { transform: rotate(90deg) translateY(-90px); }
/* 继续添加其他刻度 */
通过以上方法,可以实现一个功能完整且视觉效果良好的模拟时钟。






