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;
}
.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 {
position: absolute;
width: 12px;
height: 12px;
background: #333;
border-radius: 50%;
top: 50%;
left: 50%;
margin: -6px 0 0 -6px;
}
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时钟(无JavaScript)
如果只需要静态时钟效果,可以使用CSS伪元素和旋转:
.clock {
/* 基础样式同上 */
}
.clock::before {
content: '';
position: absolute;
width: 6px;
height: 60px;
background: #333;
left: 50%;
bottom: 50%;
margin-left: -3px;
transform: rotate(30deg); /* 指向3点 */
transform-origin: bottom center;
}
.clock::after {
content: '';
position: absolute;
width: 4px;
height: 80px;
background: #333;
left: 50%;
bottom: 50%;
margin-left: -2px;
transform: rotate(180deg); /* 指向6点 */
transform-origin: bottom center;
}
添加刻度标记
为时钟添加小时刻度:
.clock .mark {
position: absolute;
width: 3px;
height: 10px;
background: #333;
left: 50%;
bottom: 100%;
margin-left: -1.5px;
transform-origin: bottom center;
}
/* 通过旋转创建12个刻度 */
.clock .mark:nth-child(1) { transform: rotate(30deg); }
.clock .mark:nth-child(2) { transform: rotate(60deg); }
/* ...继续添加其他刻度 */
这些方法可以组合使用,创建出不同风格的CSS时钟效果。动态版本需要JavaScript配合更新指针角度,而静态版本则适合展示固定时间。







