用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;
}
.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: red;
}
.center {
width: 12px;
height: 12px;
background: #333;
border-radius: 50%;
position: absolute;
top: 94px;
left: 94px;
}
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: 8px;
height: 15px;
background: #333;
left: 96px;
top: 10px;
transform-origin: bottom center;
}
.clock::after {
content: '';
position: absolute;
width: 8px;
height: 15px;
background: #333;
left: 96px;
bottom: 10px;
transform-origin: top center;
}
/* 添加更多刻度可以使用伪元素或额外元素 */
优化钟表外观
通过CSS渐变和阴影增强视觉效果:
.clock {
background: radial-gradient(circle, #f5f5f5, #e0e0e0);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
}
.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);
}
这个实现创建了一个基本的模拟钟表,包含时针、分针和秒针,每秒自动更新。可以根据需要调整尺寸、颜色和样式。






