用javascript实现动态时钟
时间: 2023-10-24 12:05:54 浏览: 105
以下是JavaScript实现动态时钟的代码:
HTML:
```html
<!DOCTYPE html>
<html>
<head>
<title>动态时钟</title>
<style>
body {
background-color: #f1f1f1;
}
.clock {
margin: 50px auto;
width: 200px;
height: 200px;
border-radius: 50%;
background-color: white;
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.1);
position: relative;
}
.hour-hand {
position: absolute;
top: 50%;
left: 50%;
width: 6px;
height: 50px;
background-color: black;
transform-origin: bottom center;
transform: translateX(-50%) rotate(0deg);
animation: hourAnim 43200s linear infinite;
}
.minute-hand {
position: absolute;
top: 50%;
left: 50%;
width: 4px;
height: 80px;
background-color: black;
transform-origin: bottom center;
transform: translateX(-50%) rotate(0deg);
animation: minuteAnim 3600s linear infinite;
}
.second-hand {
position: absolute;
top: 50%;
left: 50%;
width: 2px;
height: 100px;
background-color: red;
transform-origin: bottom center;
transform: translateX(-50%) rotate(0deg);
animation: secondAnim 60s linear infinite;
}
@keyframes hourAnim {
from {
transform: translateX(-50%) rotate(0deg);
}
to {
transform: translateX(-50%) rotate(360deg);
}
}
@keyframes minuteAnim {
from {
transform: translateX(-50%) rotate(0deg);
}
to {
transform: translateX(-50%) rotate(360deg);
}
}
@keyframes secondAnim {
from {
transform: translateX(-50%) rotate(0deg);
}
to {
transform: translateX(-50%) rotate(360deg);
}
}
.clock-center {
position: absolute;
top: 50%;
left: 50%;
width: 10px;
height: 10px;
background-color: black;
border-radius: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="clock">
<div class="hour-hand"></div>
<div class="minute-hand"></div>
<div class="second-hand"></div>
<div class="clock-center"></div>
</div>
<script src="clock.js"></script>
</body>
</html>
```
JavaScript:
```javascript
function updateClock() {
const now = new Date();
const hour = now.getHours();
const minute = now.getMinutes();
const second = now.getSeconds();
const hourDegree = (hour % 12) * 30 + (minute / 60) * 30;
const minuteDegree = minute * 6;
const secondDegree = second * 6;
document.querySelector(".hour-hand").style.transform = `translateX(-50%) rotate(${hourDegree}deg)`;
document.querySelector(".minute-hand").style.transform = `translateX(-50%) rotate(${minuteDegree}deg)`;
document.querySelector(".second-hand").style.transform = `translateX(-50%) rotate(${secondDegree}deg)`;
}
setInterval(updateClock, 1000);
```
这个代码通过 `setInterval` 方法每秒更新一次时钟, `updateClock` 函数获取当前时间并计算出每个指针应该旋转的角度,然后通过设置 `transform` 属性来旋转指针。其中,时针每小时旋转30度,分针每分钟旋转6度,秒针每秒钟旋转6度。
在HTML文件中,我们定义了一个时钟的容器 `.clock`,并在其中添加了时针、分针、秒针和中心点。每个指针都有自己的类名和CSS样式,也有自己的动画效果。其中,时针的动画总时长为43200秒(12小时),分针的动画总时长为3600秒(1小时),秒针的动画总时长为60秒(1分钟)。这样可以让指针在一定的时间内完成一圈的旋转。
阅读全文