当前位置:首页 > CSS

css制作小时钟

2026-03-11 20:25:50CSS

使用CSS和HTML制作小时钟

通过CSS的transformanimation属性结合HTML结构,可以创建一个动态的模拟时钟。以下是实现步骤:

HTML结构

创建时钟的基本框架,包括表盘、时针、分针和秒针:

css制作小时钟

<div class="clock">
  <div class="clock-face">
    <div class="hand hour-hand"></div>
    <div class="hand min-hand"></div>
    <div class="hand second-hand"></div>
  </div>
</div>

CSS样式

设置时钟的外观和动画效果:

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

.clock-face {
  width: 100%;
  height: 100%;
  position: relative;
}

.hand {
  width: 50%;
  height: 6px;
  background: #333;
  position: absolute;
  top: 50%;
  transform-origin: 100%;
  transform: rotate(90deg);
  transition: all 0.05s cubic-bezier(0.1, 2.7, 0.58, 1);
}

.hour-hand {
  width: 30%;
  left: 20%;
}

.min-hand {
  width: 40%;
  left: 10%;
}

.second-hand {
  height: 2px;
  background: red;
}

JavaScript动态更新

使用JavaScript获取当前时间并更新指针角度:

css制作小时钟

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

  const secondDegrees = (seconds / 60) * 360 + 90;
  const minDegrees = (mins / 60) * 360 + (seconds / 60) * 6 + 90;
  const hourDegrees = (hours / 12) * 360 + (mins / 60) * 30 + 90;

  document.querySelector('.second-hand').style.transform = `rotate(${secondDegrees}deg)`;
  document.querySelector('.min-hand').style.transform = `rotate(${minDegrees}deg)`;
  document.querySelector('.hour-hand').style.transform = `rotate(${hourDegrees}deg)`;
}

setInterval(updateClock, 1000);
updateClock(); // 初始化

添加刻度标记

为表盘添加小时刻度:

.clock-face::after {
  content: '';
  width: 15px;
  height: 15px;
  background: #333;
  border-radius: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* 使用伪元素或额外HTML元素添加12个刻度 */

优化动画效果

通过CSS的transition-timing-function实现秒针的跳动效果:

.second-hand {
  transition-timing-function: cubic-bezier(0.1, 2.7, 0.58, 1);
}

完整实现将显示一个带有平滑动画的模拟时钟,指针会实时反映当前时间。通过调整CSS变量如颜色、尺寸等,可以自定义时钟外观。

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

相关文章

css制作春季踏青

css制作春季踏青

使用CSS制作春季踏青主题效果 背景设计 通过渐变背景模拟春日天空,使用柔和的色调如浅蓝、淡绿和粉色。可以添加云朵或小鸟的剪影作为装饰元素。 body { background: linear-…

制作css导航栏实验

制作css导航栏实验

实验目标 通过CSS实现一个水平导航栏,包含悬停效果和响应式设计。 基本HTML结构 创建一个简单的导航栏HTML结构,使用<ul>和<li>标签组织导航项:…

css 制作输入框

css 制作输入框

基础输入框样式 使用 input 或 textarea 元素创建输入框,通过 CSS 设置边框、圆角、内边距和背景色: .input-basic { border: 1px solid #ccc…

css 制作购物网站

css 制作购物网站

布局设计 使用CSS Grid或Flexbox创建响应式布局。Grid适合整体页面结构,Flexbox适合局部组件排列。定义网格模板区域,如头部、导航、商品展示区、侧边栏和页脚。 .containe…

简历制作css

简历制作css

简历制作CSS技巧 使用CSS美化简历可以提升视觉效果和专业性。以下是一些关键方法和代码示例: 基础样式设置 body { font-family: 'Arial', sans-serif;…

css导航制作

css导航制作

水平导航栏制作 使用无序列表 <ul> 和 <li> 标签构建基础结构,通过 CSS 移除默认样式并设置横向排列: <ul class="horizontal-nav"…