Z
ZHANK
CSS3 动效

动画 animation

@keyframes 定义动画、animation 属性、循环/反向/暂停

动画 animation

@keyframes + animation 让 CSS 能做真正的关键帧动画——比 transition 强大得多。

学完本章你将: 掌握 @keyframes 关键帧、animation 属性、循环/反向/暂停。


@keyframes 定义动画

css
@keyframes slideIn {
  from {
    transform: translateX(-100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 或百分比 */
@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-20px); }
}

应用动画

css
.animated {
  animation-name: slideIn;
  animation-duration: 0.5s;
  animation-timing-function: ease;
  animation-delay: 0.2s;
  animation-iteration-count: infinite;   /* 无限循环 / 数字 */
  animation-direction: alternate;        /* 来回播放 */
  animation-fill-mode: forwards;         /* 停在最后一帧 */
  animation-play-state: running;         /* running/paused */
}

/* 简写 */
.box { animation: slideIn 0.5s ease 0.2s 3 alternate forwards; }

实用动画

css
/* 淡入 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

/* 旋转加载 */
@keyframes spin {
  to { transform: rotate(360deg); }
}
.loader {
  animation: spin 1s linear infinite;
  border: 3px solid #eee;
  border-top-color: #4CAF50;
  border-radius: 50%;
  width: 40px; height: 40px;
}

/* 脉冲 */
@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}