功能说明
示例定义多组关键帧:fadeIn 改变透明度,slideInLeft 同时位移与淡入,bounce 用多个百分比节点做弹跳,pulse 缩放呼吸,spin 旋转出加载圈。它还通过 nth-child 给列表项设置递增延迟,形成交错入场,并在用户偏好减少动态效果时压缩动画时长。
关键代码
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }定义起止状态,类中用animation: fadeIn 0.5s ease-out forwards应用,forwards让动画停在末帧。cubic-bezier(0.16, 1, 0.3, 1)提供先快后缓的自定义缓动,适合侧滑入场。0%, 20%, 50%, 80%, 100%与40%、60%组合出弹跳轨迹,infinite让动画循环。- 加载圈用等宽高、圆形边框和单边高亮色,再旋转 360 度。
.stagger > *:nth-child(n)逐个设置animation-delay,实现 0.1 秒递增的错峰效果。@media (prefers-reduced-motion: reduce)把时长压到 0.01ms、循环次数设为 1,照顾对动态敏感的用户。
使用注意
优先对 transform 和 opacity 做动画,避免触发布局重排和重绘;示例中的宽度、边框等静态属性不参与动画。无限动画会持续消耗资源,页面不可见时应考虑暂停。forwards 与 both 的区别在于后者还会应用起始帧,交错延迟要配合填充模式才能避免闪烁。务必保留减少动态效果的媒体查询。
验证方式
在浏览器中打开包含这些类的页面,观察淡入、侧滑、弹跳、脉冲和旋转效果;给列表添加多个子元素确认延迟递增。开启系统“减少动态效果”后刷新,动画应几乎立即结束并保持最终状态。
代码示例
/* Fade in animation */
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.fade-in {
animation: fadeIn 0.5s ease-out forwards;
}
/* Slide in from left */
@keyframes slideInLeft {
from {
transform: translateX(-100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
.slide-in {
animation: slideInLeft 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}
/* Bounce effect */
@keyframes bounce {
0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
40% { transform: translateY(-30px); }
60% { transform: translateY(-15px); }
}
.bounce {
animation: bounce 1s infinite;
}
/* Pulse animation */
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.05); }
}
.pulse {
animation: pulse 2s ease-in-out infinite;
}
/* Loading spinner */
@keyframes spin {
to { transform: rotate(360deg); }
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
/* Staggered animation */
.stagger > * {
animation: slideInLeft 0.5s ease-out both;
}
.stagger > *:nth-child(1) { animation-delay: 0.1s; }
.stagger > *:nth-child(2) { animation-delay: 0.2s; }
.stagger > *:nth-child(3) { animation-delay: 0.3s; }
.stagger > *:nth-child(4) { animation-delay: 0.4s; }
/* Respect reduced motion */
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
}
}