用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;
background: white;
}
.hour-hand, .minute-hand, .second-hand {
position: absolute;
background: #333;
transform-origin: bottom center;
left: 50%;
bottom: 50%;
}
.hour-hand {
width: 6px;
height: 60px;
margin-left: -3px;
}
.minute-hand {
width: 4px;
height: 80px;
margin-left: -2px;
}
.second-hand {
width: 2px;
height: 90px;
margin-left: -1px;
background: red;
}
.center {
width: 12px;
height: 12px;
background: #333;
border-radius: 50%;
position: absolute;
left: 50%;
top: 50%;
margin-left: -6px;
margin-top: -6px;
}
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%
);
}
优化版本(使用CSS变量)
:root {
--clock-size: 200px;
--clock-border: 10px;
}
.clock {
width: var(--clock-size);
height: var(--clock-size);
border: var(--clock-border) solid #333;
/* 其余样式保持不变 */
}
纯CSS时钟(无JavaScript)
虽然无法完全动态更新,但可以使用CSS动画模拟:
.second-hand {
animation: rotate 60s linear infinite;
}
.minute-hand {
animation: rotate 3600s linear infinite;
}
.hour-hand {
animation: rotate 43200s linear infinite;
}
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
以上代码组合可以创建一个功能完整的CSS时钟。HTML提供结构,CSS负责样式和基本动画,JavaScript实现动态时间更新。可以根据需要调整尺寸、颜色和样式细节。






