
CSS3 动画分两种:transition 过渡动画(简单状态变化)、@keyframes 关键帧动画(复杂循环/多段动画),纯CSS无需JS,浏览器硬件加速、性能极高。
适合:hover、点击、样式切换平滑渐变,只有起始+结束2个状态
/* 复合写法:属性 时长 速度曲线 延迟 */
transition: all 0.5s ease 0.1s;all:所有变化属性都过渡(也可单独写width、opacity、transform)0.5s:动画时长(秒s/毫秒ms)ease:缓动曲线(匀速linear、先慢后快ease-in、先快后慢ease-out)0.1s:延迟多久执行.box {
width: 100px;
height: 100px;
background: red;
/* 开启过渡 */
transition: transform 0.3s, background 0.3s;
}
.box:hover {
transform: scale(1.2); /* 放大1.2倍 */
background: blue;
}核心两步:1. @keyframes 定义动画每帧样式 → 2. animation 绑定到元素
/* 动画名:move */
@keyframes move {
from { transform: translateX(0); } /* 0% 起点 */
50% { transform: translateX(150px); } /* 中间状态 */
to { transform: translateX(300px); } /* 100% 终点 */
}from = 0%,to = 100%.box {
/* 动画名 时长 缓动 延迟 循环次数 方向 填充模式 */
animation: move 2s ease 0s infinite alternate;
}animation-name:动画名称(和@keyframes一一对应)animation-duration:单次时长(必写)animation-timing-function:速度曲线linear 匀速、ease 默认、ease-in 渐快、ease-out 渐慢、ease-in-out 两头慢中间快animation-delay:动画延迟开始时间animation-iteration-count:循环次数infinite 无限循环animation-direction:播放方向normal 正向(默认)reverse 反向alternate 正→反交替alternate-reverse 反→正交替animation-fill-mode:动画结束状态none 回到初始forwards 保持最后一帧backwards 等待延迟时就应用第一帧animation-play-state:running播放 / paused暂停@keyframes rotate {
0% { transform: rotate(0deg); background: red; }
50% { transform: rotate(180deg); background: yellow; }
100% { transform: rotate(360deg); background: blue; }
}
.box {
width: 100px;
height: 100px;
animation: rotate 3s linear infinite forwards;
}配合动画做位移、旋转、缩放、倾斜
translate(x,y) 平移transform: translate(50px, 20px) rotate(45deg) scale(1.1);rotate(deg) 旋转scale(n) 缩放skew(deg) 倾斜对比项 | transition 过渡 | @keyframes 关键帧 |
|---|---|---|
状态 | 只有起点、终点 | 任意多中间帧 |
触发 | hover/JS 状态改变 | 自动播放、无限循环 |
复杂度 | 简单交互动画 | 轮播、弹跳、轨迹、循环动画 |
语法 | 极简 | 灵活强大 |
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.box { animation: fadeIn 1s ease forwards; }@keyframes bounce {
0%,100% { transform: translateY(0); }
50% { transform: translateY(-30px); }
}
.box { animation: bounce 1s infinite ease-in-out; }主流浏览器全兼容,无需前缀;老旧webkit内核可加:
@-webkit-keyframes xxx {}
-webkit-animation: xxx;原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。