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;
background: #fff;
}
.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-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: 4px;
height: 15px;
background: #333;
left: 50%;
top: 10px;
margin-left: -2px;
transform-origin: 50% 90px;
}
/* 创建12个刻度 */
.clock {
position: relative;
}
.clock::before {
content: '';
position: absolute;
width: 4px;
height: 15px;
background: #333;
left: 50%;
top: 10px;
margin-left: -2px;
transform-origin: 50% 90px;
}
/* 使用伪元素创建所有刻度 */
.clock::after {
content: '';
position: absolute;
width: 2px;
height: 8px;
background: #666;
left: 50%;
top: 15px;
margin-left: -1px;
transform-origin: 50% 85px;
}
/* 创建60个刻度 */
.clock {
counter-reset: ticks 60;
}
.clock::after {
counter-increment: ticks -1;
transform: rotate(calc(var(--i) * 6deg));
}
/* 需要JavaScript动态添加刻度 */
完整实现建议
- 将上述HTML、CSS和JavaScript代码整合到一个文件中
- 可以根据需要调整时钟大小、颜色和样式
- 考虑添加数字标记或更精美的设计
- 可以添加日期显示功能
这种方法创建的时钟会每秒更新一次,显示当前时间。CSS负责外观样式,JavaScript处理动态旋转逻辑。







