# CSS3中keyframes怎么用
## 一、什么是keyframes
`@keyframes`是CSS3動畫的核心規則,用于創建復雜的逐幀動畫效果。通過定義動畫序列中特定時間點的樣式狀態,瀏覽器會自動補間生成平滑的過渡效果。
### 基本語法
```css
@keyframes 動畫名稱 {
0% { /* 起始狀態 */ }
50% { /* 中間狀態 */ }
100% { /* 結束狀態 */ }
}
百分比表示動畫進度:
@keyframes slidein {
from { transform: translateX(0); }
to { transform: translateX(100px); }
}
通過animation屬性綁定:
.element {
animation: slidein 2s ease-in-out;
}
@keyframes colorchange {
0% { background: red; }
33% { background: yellow; }
66% { background: blue; }
100% { background: green; }
}
完整語法示例:
.element {
animation:
name duration timing-function delay
iteration-count direction fill-mode;
}
| 屬性 | 描述 | 示例值 |
|---|---|---|
| animation-name | 指定@keyframes名稱 | myAnimation |
| animation-duration | 動畫持續時間 | 2s, 500ms |
| animation-timing-function | 速度曲線 | ease, linear, cubic-bezier(.1,.2,.3,.4) |
| animation-delay | 開始延遲 | 1s |
| animation-iteration-count | 播放次數 | 3, infinite |
| animation-direction | 播放方向 | normal, reverse, alternate |
| animation-fill-mode | 結束狀態 | forwards, backwards |
| animation-play-state | 暫停/運行 | paused, running |
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-100px); }
}
.ball {
animation: bounce 1s infinite alternate;
}
@keyframes breathing {
0% { opacity: 0.5; transform: scale(0.9); }
50% { opacity: 1; transform: scale(1.1); }
100% { opacity: 0.5; transform: scale(0.9); }
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.loader {
animation: spin 1s linear infinite;
}
.element {
animation:
slide 2s ease-out,
fade 1.5s ease-in 0.5s;
}
創建幀動畫效果:
@keyframes typing {
from { width: 0 }
to { width: 100% }
}
.text {
animation: typing 3s steps(30);
}
@keyframes smoothMove {
to { transform: translate3d(100px,0,0); }
}
@-webkit-keyframes {}
@-moz-keyframes {}
@-o-keyframes {}
if('animation' in document.body.style) {
// 支持標準語法
}
element.style.animationPlayState = 'paused';
CSS3的@keyframes為網頁動畫提供了強大的解決方案。通過本文的學習,您應該已經掌握了從基礎定義到高級應用的完整知識體系。建議通過實際項目不斷練習,結合JavaScript可以實現更復雜的交互式動畫效果。
提示:最新CSS規范支持
@keyframes與CSS Houdini API結合,可以創建更動態的動畫控制,這是值得關注的前沿技術方向。 “`
(注:本文實際約1200字,可根據需要擴展具體案例或添加更多示例代碼)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。