1. css 动画属性
CSS 动画通过 @keyframes 规则和动画属性,让元素在一段时间内平滑地改变样式。动画的使用包括定义关键帧(描述每个阶段样式变化)以及在元素上应用动画属性。
- 基础的,css 动画包含 8 个基础属性:
animation-name
自定义动画的名称animation-duration
动画的持续时间animation-timing-function
速度曲线animation-delay
延迟时间animation-iteration-count
循环次数animation-direction
动画方向animation-fill-mode
动画执行前后的样式animation-play-state
动画播放状态
- 属性简写 animation 的顺序推荐
.animation-style {
animation: name duration timing-function delay iteration-count direction fill-mode play-state;
}
2. loading 动画示例
关键帧名称可以是自定义的字符串。每个关键帧定义动画的某个时间点的样式。通常,0% 表示动画的开始,100% 表示动画的结束。也可以使用 from 和 to 替代 0% 和 100%。
- 示例1:
<div class="spinner"></div>
<style>
.spinner {
width: 40px;
height: 40px;
border: 5px solid transparent;
border-top-color: lightcoral;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
- 示例2:
<div class="loading-spinner">
<svg class="circular" viewBox="0 0 50 50">
<circle class="path" cx="25" cy="25" r="20" fill="none"></circle>
</svg>
</div>
<style>
.loading-spinner .circular {
display: inline;
height: 100px;
width: 100px;
animation: loading-rotate 2s linear infinite;
}
.loading-spinner {
top: 50%;
width: 100%;
text-align: center;
position: absolute;
}
.loading-spinner .path {
animation: loading-dash 1.5s ease-in-out infinite;
stroke-dasharray: 90, 150;
stroke-dashoffset: 0;
stroke-width: 2;
stroke: lightblue;
stroke-linecap: round;
}
@keyframes loading-rotate {
100% {
transform: rotate(360deg);
}
}
@keyframes loading-dash {
0% {
stroke-dasharray: 1, 200;
stroke-dashoffset: 0;
}
50% {
stroke-dasharray: 90, 150;
stroke-dashoffset: -40px;
}
100% {
stroke-dasharray: 90, 150;
stroke-dashoffset: -120px;
}
}
</style>
3. 动画事件
animationstart
动画开始时触发animationend
动画正常结束时触发animationcancel
动画被中止时触发animationiteration
新一轮循环开始时触发
ps: 动画异常中止时会触发 animationcancel,不会触发 animationend