欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > CSS3 动画基础与技巧

CSS3 动画基础与技巧

2025/6/20 11:38:01 来源:https://blog.csdn.net/teeeeeeemo/article/details/148678800  浏览:    关键词:CSS3 动画基础与技巧

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

1. 基础动画语法

/* 定义关键帧动画 */
@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. 常用动画示例

淡入淡出

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

移动元素

@keyframes move {0%   { transform: translateX(0); }100% { transform: translateX(200px); }
}

旋转

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

缩放效果

@keyframes pulse {0% { transform: scale(1); }50% { transform: scale(1.2); }100% { transform: scale(1); }
}

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

.element {animation: pulse 1.5s infinite,move 3s alternate;
}

5. 进阶技巧

使用steps()实现逐帧动画

@keyframes typing {from { width: 0 }to { width: 100% }
}.text {animation: typing 4s steps(40) infinite;
}

暂停/播放动画

.element {animation-play-state: paused; /* 通过JS控制 */
}.element:hover {animation-play-state: running;
}

6. 性能优化

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

7. 浏览器兼容前缀

@-webkit-keyframes example { ... }
.element {-webkit-animation: example 2s;animation: example 2s;
}

完整示例:弹跳球效果

<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>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词