当前位置:首页 > CSS

css制作时钟

2026-01-08 11:56:34CSS

CSS 制作时钟的方法

使用纯 CSS 和少量 JavaScript 可以制作一个动态时钟。以下是实现步骤:

HTML 结构

<div class="clock">
  <div class="hour-hand"></div>
  <div class="minute-hand"></div>
  <div class="second-hand"></div>
  <div class="center"></div>
</div>

CSS 样式

.clock {
  width: 200px;
  height: 200px;
  border: 10px solid #333;
  border-radius: 50%;
  position: relative;
  margin: 50px auto;
}

.hour-hand, .minute-hand, .second-hand {
  position: absolute;
  background: #333;
  transform-origin: bottom center;
  left: 50%;
  top: 50%;
}

.hour-hand {
  width: 6px;
  height: 50px;
  margin-left: -3px;
  margin-top: -50px;
}

.minute-hand {
  width: 4px;
  height: 80px;
  margin-left: -2px;
  margin-top: -80px;
}

.second-hand {
  width: 2px;
  height: 90px;
  margin-left: -1px;
  margin-top: -90px;
  background: red;
}

.center {
  width: 12px;
  height: 12px;
  background: #333;
  border-radius: 50%;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -6px;
  margin-top: -6px;
  z-index: 10;
}

JavaScript 动态更新

function updateClock() {
  const now = new Date();
  const hours = now.getHours() % 12;
  const minutes = now.getMinutes();
  const seconds = now.getSeconds();

  const hourDeg = (hours * 30) + (minutes * 0.5);
  const minuteDeg = minutes * 6;
  const secondDeg = seconds * 6;

  document.querySelector('.hour-hand').style.transform = `rotate(${hourDeg}deg)`;
  document.querySelector('.minute-hand').style.transform = `rotate(${minuteDeg}deg)`;
  document.querySelector('.second-hand').style.transform = `rotate(${secondDeg}deg)`;
}

setInterval(updateClock, 1000);
updateClock();

实现原理

时钟的指针通过 CSS 的 transform: rotate() 属性实现旋转。JavaScript 计算当前时间对应的角度,每小时对应 30 度(360/12),每分钟对应 6 度(360/60),秒针同理。

transform-origin: bottom center 确保指针围绕底部中心旋转。定时器每秒更新一次指针位置,实现动态效果。

增强样式

可以添加时钟刻度和数字增强视觉效果:

css制作时钟

.clock::before {
  content: '';
  position: absolute;
  width: 4px;
  height: 12px;
  background: #333;
  left: 50%;
  top: 10px;
  margin-left: -2px;
}

/* 添加其他刻度类似 */

这种方法创建的时钟简洁高效,适合大多数网页场景。

标签: 时钟css
分享给朋友:

相关文章

纯css制作tab菜单

纯css制作tab菜单

纯CSS制作Tab菜单的方法 使用radio input控制切换 通过<input type="radio">和<label>元素配合实现无JavaScript的Tab切换效果…

css制作

css制作

CSS 基础语法 CSS(层叠样式表)用于描述HTML元素的样式。一个基本的CSS规则由选择器和声明块组成。选择器指定要样式化的HTML元素,声明块包含一个或多个属性-值对,用花括号 {} 包裹。…

制作css

制作css

制作CSS的基础方法 CSS(层叠样式表)用于控制网页的样式和布局。以下是创建和使用CSS的基本方法。 内联样式 直接在HTML元素的style属性中编写CSS代码。适用于单个元素的样式调整。…

css制作工具

css制作工具

CSS 制作工具推荐 在线 CSS 生成器 CSS Generator(cssgenerator.org):提供边框、阴影、渐变等常见样式的可视化生成,支持实时预览和代码复制。 EnjoyC…

css制作角标

css制作角标

使用伪元素创建角标 通过 ::before 或 ::after 伪元素生成角标,结合绝对定位调整位置。示例代码: .superscript { position: relative; dis…

css制作滑动切换

css制作滑动切换

使用CSS Transitions实现滑动切换 通过CSS的transition属性结合transform可以实现平滑的滑动效果。设置一个容器元素,内部放置需要滑动的内容,通过改变transform:…