帮我写一个JS罗盘时钟
时间: 2024-05-12 13:17:06 浏览: 114
好的,以下是一个简单的JS罗盘时钟的代码:
HTML部分:
```html
<div class="clock-wrap">
<div class="clock">
<div class="hour-hand"></div>
<div class="minute-hand"></div>
<div class="second-hand"></div>
<div class="center"></div>
</div>
</div>
```
CSS部分:
``` css
.clock-wrap {
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
}
.clock {
position: relative;
width: 100%;
height: 100%;
border-radius: 50%;
border: 2px solid black;
}
.hour-hand,
.minute-hand,
.second-hand {
position: absolute;
background-color: black;
transform-origin: bottom center;
}
.hour-hand {
top: 50%;
left: 50%;
width: 6px;
height: 50px;
margin-left: -3px;
}
.minute-hand {
top: 50%;
left: 50%;
width: 3px;
height: 70px;
margin-left: -1.5px;
}
.second-hand {
top: 50%;
left: 50%;
width: 1px;
height: 80px;
margin-left: -0.5px;
}
.center {
position: absolute;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: black;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
```
JS部分:
```javascript
function tick() {
const date = new Date();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
const hourDeg = hour * 30 + minute / 2;
const minuteDeg = minute * 6;
const secondDeg = second * 6;
const hourHand = document.querySelector('.hour-hand');
const minuteHand = document.querySelector('.minute-hand');
const secondHand = document.querySelector('.second-hand');
hourHand.style.transform = `rotate(${hourDeg}deg)`;
minuteHand.style.transform = `rotate(${minuteDeg}deg)`;
secondHand.style.transform = `rotate(${secondDeg}deg)`;
}
setInterval(tick, 1000);
```
这样就完成了一个基本的JS罗盘时钟,在HTML中添加以上代码,即可显示一个时钟,每秒钟的指针也会动态运动。
阅读全文