js css制作时钟
使用JavaScript和CSS制作时钟
HTML结构
创建一个基本的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;
background-color: #fff;
}
.hour-hand, .minute-hand, .second-hand {
position: absolute;
left: 50%;
bottom: 50%;
transform-origin: 50% 100%;
}
.hour-hand {
width: 6px;
height: 50px;
background-color: #000;
margin-left: -3px;
}
.minute-hand {
width: 4px;
height: 80px;
background-color: #555;
margin-left: -2px;
}
.second-hand {
width: 2px;
height: 90px;
background-color: #f00;
margin-left: -1px;
}
.center {
width: 12px;
height: 12px;
background-color: #333;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
margin-left: -6px;
margin-top: -6px;
}
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();
优化时钟刻度
添加时钟刻度以增强视觉效果。

.clock::after {
content: '';
position: absolute;
top: 10px;
left: 50%;
width: 4px;
height: 15px;
background-color: #333;
margin-left: -2px;
}
.clock::before {
content: '';
position: absolute;
top: 50%;
right: 10px;
width: 15px;
height: 4px;
background-color: #333;
margin-top: -2px;
}
完整实现
将HTML、CSS和JavaScript代码整合到一个文件中,确保时钟能够实时更新并显示当前时间。通过调整CSS样式和JavaScript逻辑,可以进一步自定义时钟的外观和行为。






