js实现钟表
使用JavaScript实现钟表
以下是一个简单的JavaScript钟表实现,包含时针、分针和秒针的动态效果。
HTML结构
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Clock</title>
<style>
#clock {
width: 200px;
height: 200px;
border: 10px solid #333;
border-radius: 50%;
position: relative;
margin: 50px auto;
}
.hand {
position: absolute;
left: 50%;
bottom: 50%;
transform-origin: bottom center;
}
#hour {
width: 6px;
height: 50px;
background: #333;
margin-left: -3px;
}
#minute {
width: 4px;
height: 70px;
background: #666;
margin-left: -2px;
}
#second {
width: 2px;
height: 90px;
background: red;
margin-left: -1px;
}
</style>
</head>
<body>
<div id="clock">
<div id="hour" class="hand"></div>
<div id="minute" class="hand"></div>
<div id="second" class="hand"></div>
</div>
<script src="clock.js"></script>
</body>
</html>
JavaScript代码 (clock.js)
function updateClock() {
const now = new Date();
const hour = now.getHours() % 12;
const minute = now.getMinutes();
const second = now.getSeconds();
const hourDegrees = (hour * 30) + (minute * 0.5);
const minuteDegrees = minute * 6;
const secondDegrees = second * 6;
document.getElementById('hour').style.transform = `rotate(${hourDegrees}deg)`;
document.getElementById('minute').style.transform = `rotate(${minuteDegrees}deg)`;
document.getElementById('second').style.transform = `rotate(${secondDegrees}deg)`;
}
setInterval(updateClock, 1000);
updateClock(); // 立即执行一次以避免初始延迟
实现原理
时钟通过获取当前时间来计算时针、分针和秒针的旋转角度。每小时对应30度(360度/12小时),每分钟对应6度(360度/60分钟),每秒也对应6度。

时针的旋转考虑了分钟的影响,每分钟会使时针移动0.5度(30度/60分钟)。使用CSS的transform属性来旋转指针,transform-origin设置为底部中心点作为旋转支点。

扩展功能
可以添加数字时间显示或美化时钟外观:
// 在updateClock函数中添加
const timeString = now.toLocaleTimeString();
document.getElementById('time-display').textContent = timeString;
对应的HTML添加:
<div id="time-display" style="text-align: center; font-size: 24px;"></div>
这个实现使用了纯JavaScript和CSS,不需要任何外部库,可以在现代浏览器中流畅运行。






