CSS3 动画基础与技巧

CSS3动画允许你创建平滑、高性能的动画效果,无需JavaScript。主要通过@keyframes和animation属性实现。以下是详细指南:

1. 基础动画语法

css 复制代码
/* 定义关键帧动画 */
@keyframes example {
  0%   { background: red; }
  50%  { background: yellow; }
  100% { background: green; }
}

/* 应用动画 */
.element {
  animation: example 3s ease-in-out infinite;
}

2. 关键属性

属性 描述 示例值
animation-name 动画名称 example
animation-duration 动画时长 2s / 400ms
animation-timing-function 速度曲线 ease, linear, cubic-bezier(0.1, 0.7, 1.0, 0.1)
animation-delay 开始延迟 1s
animation-iteration-count 重复次数 3, infinite
animation-direction 播放方向 normal, reverse, alternate
animation-fill-mode 结束状态保留 forwards, backwards

3. 常用动画示例

淡入淡出

css 复制代码
@keyframes fade {
  from { opacity: 0; }
  to   { opacity: 1; }
}
.element {
  animation: fade 1.5s ease-in;
}

移动元素

css 复制代码
@keyframes move {
  0%   { transform: translateX(0); }
  100% { transform: translateX(200px); }
}

旋转

css 复制代码
@keyframes spin {
  to { transform: rotate(360deg); }
}
.element {
  animation: spin 2s linear infinite;
}

缩放效果

css 复制代码
@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

4. 复合动画(多个动画同时运行)

css 复制代码
.element {
  animation: 
    pulse 1.5s infinite,
    move 3s alternate;
}

5. 进阶技巧

使用steps()实现逐帧动画

css 复制代码
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

.text {
  animation: typing 4s steps(40) infinite;
}

暂停/播放动画

css 复制代码
.element {
  animation-play-state: paused; /* 通过JS控制 */
}

.element:hover {
  animation-play-state: running;
}

6. 性能优化

  • 优先使用 transform 和 opacity(不会触发重排)
  • 避免动画阻塞主线程:使用 will-change: transform;
  • 硬件加速:对移动元素添加 transform: translateZ(0);

7. 浏览器兼容前缀

css 复制代码
@-webkit-keyframes example { ... }
.element {
  -webkit-animation: example 2s;
          animation: example 2s;
}

完整示例:弹跳球效果

html 复制代码
<div class="ball"></div>

<style>
.ball {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(red, orange);
  animation: bounce 1s cubic-bezier(0.5, 0.05, 0.5, 1) infinite alternate;
}

@keyframes bounce {
  0%   { transform: translateY(0); }
  100% { transform: translateY(-100px); }
}
</style>
相关推荐
承渊政道3 小时前
Linux系统学习【Linux基础开发工具】
linux·运维·笔记·学习·centos·编辑器
承渊政道4 小时前
C++学习之旅【C++中模板进阶内容介绍】
c语言·c++·笔记·学习·visual studio
小杨同学呀呀呀呀4 小时前
Ant Design Vue <a-timeline>时间轴组件失效解决方案
前端·javascript·vue.js·typescript·anti-design-vue
浅念-4 小时前
C语言——动态内存管理
c语言·开发语言·c++·笔记·学习
华玥作者12 小时前
[特殊字符] VitePress 对接 Algolia AI 问答(DocSearch + AI Search)完整实战(下)
前端·人工智能·ai
Mr Xu_12 小时前
告别冗长 switch-case:Vue 项目中基于映射表的优雅路由数据匹配方案
前端·javascript·vue.js
前端摸鱼匠12 小时前
Vue 3 的toRefs保持响应性:讲解toRefs在解构响应式对象时的作用
前端·javascript·vue.js·前端框架·ecmascript
lang2015092812 小时前
JSR-340 :高性能Web开发新标准
java·前端·servlet
ASKED_201913 小时前
Langchain学习笔记一 -基础模块以及架构概览
笔记·学习·langchain
Lois_Luo13 小时前
Obsidian + Picgo + Aliyun OSS 实现笔记图片自动上传图床
笔记·oss·图床