用js和css实现一个时钟功能
时间: 2023-05-26 11:06:55 浏览: 155
使用js+css 实现钟表的功能
HTML:
```
<div class="clock">
<div class="hour"></div>
<div class="minute"></div>
<div class="second"></div>
</div>
```
CSS:
```
.clock {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
border-radius: 50%;
background-color: #fff;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}
.hour,
.minute,
.second {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: #333;
}
.hour {
width: 50px;
height: 8px;
border-radius: 4px;
transform-origin: left center;
}
.minute {
width: 80px;
height: 6px;
border-radius: 3px;
transform-origin: left center;
}
.second {
width: 100px;
height: 4px;
border-radius: 2px;
transform-origin: left center;
}
```
JS:
```
function updateClock() {
let now = new Date();
let hour = now.getHours() % 12; // 转换成12小时制
let minute = now.getMinutes();
let second = now.getSeconds();
// 计算时、分、秒针的旋转角度
let hourDeg = hour * 30 + minute * 0.5; // 每小时30度,每分钟0.5度
let minuteDeg = minute * 6; // 每分钟6度
let secondDeg = second * 6; // 每秒6度
// 更新时、分、秒针的角度
let hourEl = document.querySelector('.hour');
let minuteEl = document.querySelector('.minute');
let secondEl = document.querySelector('.second');
hourEl.style.transform = `rotate(${hourDeg}deg)`;
minuteEl.style.transform = `rotate(${minuteDeg}deg)`;
secondEl.style.transform = `rotate(${secondDeg}deg)`;
}
// 每秒更新一次时钟
setInterval(updateClock, 1000);
```
可以在网页中嵌入上述代码后运行,即可实现一个简单的时钟功能。
阅读全文