首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[分享]css3和JS实现时钟

发布于 2024-11-11 14:24:15
0
48

CSS3和JS是实现时钟的重要工具。CSS3的旋转变形和渐变样式能够让时钟指针平滑地旋转,JS可以让时钟数字不断更新,让时钟永远走动。/ CSS3代码 / .clock { : relative; w...

CSS3和JS是实现时钟的重要工具。CSS3的旋转变形和渐变样式能够让时钟指针平滑地旋转,JS可以让时钟数字不断更新,让时钟永远走动。

/* CSS3代码 */
.clock {
  position: relative;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: radial-gradient(circle at center, #ffd633, #f00);
}
.pointer {
  position: absolute;
  width: 4px;
  height: 100px;
  top: 50px;
  left: 50%;
  margin-left: -2px;
  background: #000;
  transform-origin: bottom center;
  transform: rotate(90deg);
  transition: transform .2s linear;
}
.second {
  background: #f00;
  height: 80px;
}
.minute {
  background: #000;
  height: 70px;
}
.hour {
  background: #000;
  height: 50px;
}
.clock .dot {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin: -4px;
  background: #000;
}

/* JS代码 */
function updateClock() {
  const time = new Date();
  const hour = time.getHours() % 12;
  const minute = time.getMinutes();
  const second = time.getSeconds();
  const hourDeg = (hour + minute / 60 + second / 3600) * 30;
  const minuteDeg = (minute + second / 60) * 6;
  const secondDeg = second * 6;
  document.querySelector('.hour').style.transform = `rotate(${hourDeg}deg)`;
  document.querySelector('.minute').style.transform = `rotate(${minuteDeg}deg)`;
  document.querySelector('.second').style.transform = `rotate(${secondDeg}deg)`;
  setTimeout(updateClock, 1000);
}
updateClock(); 
评论
一个月内的热帖推荐
91云脑
Lv.1普通用户

62849

帖子

14

小组

291

积分

赞助商广告
站长交流